As you may know, both Kotlin and Java have a feature called sealed classes. Let's play a little with them.
Kotlin sealed classes
Kotlin goes first. What do you think will be printed here?
sealed class Hobbit
class Frodo : Hobbit()
fun main() {
val hobbitClass = Hobbit::class
println("Hobbit class: isAbstract=${hobbitClass.isAbstract}, isSealed=${hobbitClass.isSealed}")
val frodoClass = Frodo::class
println("Frodo class: isAbstract=${frodoClass.isAbstract}, isSealed=${frodoClass.isSealed}")
}
Output:
Hobbit class: isAbstract=false, isSealed=true
Frodo class: isAbstract=false, isSealed=false
According to Kotlin documentation
A sealed class is abstract by itself
However, note that isAbstract
for a sealed class returns false
! So, if you want to check if the class is effectively abstract, you need to check both isAbstract
and isSealed
.
Alright, what if we explicitly add the abstract
keyword on a sealed class? What will be printed then?
abstract sealed class Human
fun main() {
val humanClass = Human::class
println("Human class: isAbstract=${humanClass.isAbstract}, isSealed=${humanClass.isSealed}")
}
Output:
Human class: isAbstract=false, isSealed=true
So, nothing has actually changed.
And if we simply take an abstract class, what will be the result?
abstract class Maiar
fun main() {
val maiarClass = Maiar::class
println("Maiar class: isAbstract=${maiarClass.isAbstract}, isSealed=${maiarClass.isSealed}")
}
Output:
Maiar class: isAbstract=true, isSealed=false
Good, nothing unexpected here.
Java sealed classes
Okay, what about Java?
With Java it is very simple: you will not be caught by isAbstract
because the Class
class has no such a function. And isSealed
works the same way as in Kotlin:
sealed class Hobbit {}
final class Frodo extends Hobbit {}
public class TestClassProperties {
void main() {
var hobbitClass = Hobbit.class;
System.out.println(STR."Hobbit class: isSealed=\{hobbitClass.isSealed()}");
var frodoClass = Frodo.class;
System.out.println(STR."Frodo class: isSealed=\{frodoClass.isSealed()}");
}
}
Output:
Hobbit class: isSealed=true
Frodo class: isSealed=false
Dream your code, code your dream.
Top comments (0)