How do you define a sealed class in Kotlin?
Defining a sealed class in Kotlin involves using the sealed modifier before the class keyword. Additionally, all subclasses of a sealed class must be declared within the same file where the sealed class is declared.
Here’s an example of a sealed class named Result with two subclasses, Success and Error:
kotlin sealed class Result { data class Success(val data: String) : Result() data class Error(val message: String) : Result() }
In this example, Result is a sealed class with two sealed subclasses, Success and Error. These subclasses encapsulate different outcomes of an operation, providing a clear and structured representation of possible results.
Sealed classes promote type safety and exhaustive handling, ensuring that all possible subclasses are accounted for in when expressions or pattern matching, thereby reducing the likelihood of runtime errors and improving code robustness.