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()
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 withis 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)
- 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 forsealed interface
s a lot :) )
Top comments (0)