1. Overview

In this quick tutorial, we’re going to learn how to find all subclasses of a particular sealed class in Kotlin.

2. Getting Subclasses of a Sealed Class

As we know, sealed classes and interfaces are inheritance hierarchies with a simple restriction: Only classes and interfaces in the same package can extend them. Therefore, all the subclasses of a particular sealed class are known at compile-time.

Let’s consider a simple hierarchy of classes as an example:

sealed class Expr(val keyword: String)
class ForExpr : Expr("for")
class IfExpr : Expr("if")
class WhenExpr : Expr("when")
class DeclarationExpr : Expr("val")

Here, we have one sealed class with four concrete extensions.

As of Kotlin 1.3, in order to find all subclasses of a sealed class, we can use the sealedSubclasses property:

val subclasses: List<KClass<*>> = Expr::class.sealedSubclasses

  ForExpr::class, IfExpr::class, WhenExpr::class, DeclarationExpr::class

As shown above, we have to find the KClass<T> of the superclass and then use the sealedSubclasses property on it. Here, we’re also verifying that there are four subclasses of the Expr superclass.

3. Conclusion

In this tutorial, we learned how to find the subclasses of a particular sealed class in Kotlin.

As usual, all the examples are available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.