The following article describes Sealed Class in Kotlin.
Basically, the sealed class in Kotlin restricts the creation of its subclasses. In general, a sealed class is a class that can only be subclassed within the same file where it’s declared. In other words, the sealed class and its subclass must be within the same file. Therefore, sealed classes are commonly used in Kotlin to create restricted class hierarchies that provide better control over the inheritance. The following example demonstrates it.
sealed class Result {
data class Success(val value: Int) : Result()
data class Failure(val error: Throwable) : Result()
}
So, Result
is a sealed class that has two subclasses, Success
and Failure
. In fact, both Success
and Failure
are data classes that extend Result
. Notice that both Success
and Failure
are declared inside the Result
class and are therefore restricted to that file.
Furthermore, one common use case for sealed classes is with when
expressions. Since sealed classes provide a restricted hierarchy of classes, the when
expression can ensure that all possible cases are covered. Therefore, the compiler gives a warning if a case is missing. The following example shows how to use a when
expression with a sealed class.
fun processResult(result: Result)
{
when (result)
{
is Result.Success -> println("The result is ${result.value}")
is Result.Failure -> println("The error is ${result.error}")
} }
While the processResult
function takes a Result
as its argument. Inside the function, a when
expression handles the two possible cases of Result
, Success
and Failure
. Since Result
is a sealed class, the when
expression can ensure that all possible cases are covered. So, the compiler can give a warning if a case is missing.
In summary, sealed classes in Kotlin are useful for creating restricted class hierarchies. Moreover, they provide better control over the inheritance. Also, we can use them with when
expressions to ensure covering all possible cases.
Further Reading
- Android
- Angular
- ASP.NET
- AWS
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Data Science
- Data Structures and Algorithms
- Deep Learning
- Django
- Dot Net Framework
- Drones
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- Machine Learning
- MEAN Stack
- MERN Stack
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Scratch 3.0
- Smart City
- Software
- Solidity
- SQL
- TypeScript
- VB.NET
- Web Designing
- XML