Can you list the main types of objects in Kotlin and explain their differences?
sobes.tech AI
Answer from AI
In Kotlin, the main types of objects and their differences:
-
Classes (class) — templates for creating objects with state and behavior. They can have constructors, properties, methods.
-
Objects (object) — singletons, i.e., a single instance of a class created automatically. Used for storing global state or utilities.
-
Companion objects (companion object) — an object inside a class that allows creating static members (similar to static in Java).
-
Data classes (data class) — classes designed for storing data. Automatically generate methods like equals, hashCode, toString, copy.
-
Sealed classes (sealed class) — a limited set of subclasses, useful for expressing hierarchies with a fixed number of options.
-
Enum classes (enum class) — enumerations, a set of named constants.
Example of an object and a companion:
object Singleton {
val name = "I am a singleton"
}
class MyClass {
companion object {
fun create() = MyClass()
}
}
Objects are created once and used as global instances, while classes can have multiple instances.