Kotlin Sealed Class
In Kotlin, a sealed class is a class that can only be subclassed within its own file. Sealed classes are used to represent restricted class hierarchies, where the set of subclasses is known and limited.
A sealed class is defined using the sealed keyword. Here's an example:
sealed class Result<out T> class Success<T>(val data: T) : Result<T>() class Error(val message: String) : Result<Nothing>()
In this example, we define a sealed class called Result, which has two subclasses: Success and Error. The Success class has a generic type parameter T and a property data of type T. The Error class has a property message of type String and a generic type parameter of Nothing, which means it doesn't have any value.
Because Result is a sealed class, its subclasses must be defined in the same file as the sealed class. This allows the Kotlin compiler to check that all possible subclasses are covered in a when expression. Here's an example:
fun processResult(result: Result<Any>): String {
return when (result) {
is Success -> "Data: ${result.data}"
is Error -> "Error: ${result.message}"
}
}
In this example, we define a function called processResult that takes a Result<Any> parameter and returns a string. We use a when expression to check the type of the result parameter, and return a different string based on whether it is a Success or Error instance.
Sealed classes are often used to represent algebraic data types, which are types that can have multiple possible values. They provide a safe way to define a restricted class hierarchy and ensure that all possible cases are covered in pattern matching expressions.
