Junior — Middle
What are the differences between a regular class, a data class, and a sealed class in the Kotlin programming language?
sobes.tech AI
Answer from AI
In Kotlin, there are different types of classes, each with its own features:
-
Regular class (class) — a standard class that can be inherited (unless declared as final), contains properties and methods. It does not automatically generate
equals(),hashCode(),toString()methods. -
Data class (data class) — a class designed for storing data. The compiler automatically generates
equals(),hashCode(),toString(), as well ascopy()and destructuring functions. Example:
data class User(val name: String, val age: Int)
- Sealed class (sealed class) — a class that restricts the inheritance hierarchy. All subclasses must be declared in the same file. Used to represent a limited set of types, often in
whenexpressions to ensure exhaustiveness. Example:
sealed class Result {
data class Success(val data: String) : Result()
object Error : Result()
}
Thus:
- Regular class — versatile.
- Data class — for convenient storage and manipulation of data.
- Sealed class — for limited hierarchy and safe pattern matching.