DEV Community

Cover image for [Tiny] Is a sealed class abstract? Kotlin and Java way.
Petr Filaretov
Petr Filaretov

Posted on

[Tiny] Is a sealed class abstract? Kotlin and Java way.

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}")
}
Enter fullscreen mode Exit fullscreen mode

Output:
Hobbit class: isAbstract=false, isSealed=true
Frodo class: isAbstract=false, isSealed=false
Enter fullscreen mode Exit fullscreen mode

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}")
}
Enter fullscreen mode Exit fullscreen mode

Output:
Human class: isAbstract=false, isSealed=true
Enter fullscreen mode Exit fullscreen mode

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}")
}
Enter fullscreen mode Exit fullscreen mode

Output:
Maiar class: isAbstract=true, isSealed=false
Enter fullscreen mode Exit fullscreen mode

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()}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Hobbit class: isSealed=true
Frodo class: isSealed=false
Enter fullscreen mode Exit fullscreen mode


Dream your code, code your dream.

Top comments (0)