DEV Community

InsanusMokrassar
InsanusMokrassar

Posted on

About sealed classes in Kotlin

In this article I wish to say two words about sealed classes.

What is it?

Sealed classes are abstract classes with limited number of subclasses. You may get it with code like next:

sealed class Example

object ExampleObject : Example()
class ExampleSubclass : Example()
Enter fullscreen mode Exit fullscreen mode

Advantages

Kotlin compiler always know all subclasses of sealed class and it give several advantages:

  • You can use expression val result = when (something) with enumeration of all types with is Something and it will be checked by compiler:
sealed class Example

object ExampleObject : Example()
class ExampleSubclass : Example() {
    val exampleText: "Hello, world!"
}

// ...

val o = ExampleSubclass()
val message = when (o) {
    is ExampleObject -> "Just object :)"
    is ExampleSubclass -> o.exampleText
}
println(message)
Enter fullscreen mode Exit fullscreen mode
  • You are still using classes with all their opportunities: you can implement in it interfaces, add different fields and logic

Disadvantages

  • You may not extend sealed class outside of place this sealed class has been defined
  • Due to the word class in this feature name you will be unable to extend several sealed classes. (I am waiting for sealed interfaces a lot :) )

Top comments (0)