Junior — Middle
Is it possible to initialize a sealed class object in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a sealed class is a class with a restricted set of subclasses, defined in the same file. The sealed class itself is usually abstract and cannot be instantiated directly.
Only its subclasses, which specifically implement the sealed class, can be instantiated. For example:
sealed class Result {
data class Success(val data: String) : Result()
object Failure : Result()
}
val result1: Result = Result.Success("OK")
val result2: Result = Result.Failure
Thus, you cannot create an object of the sealed class directly, but you can create objects of its subclasses.