Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:
Get All Subclasses of a Sealed Class in Kotlin
Last updated: March 19, 2024
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
assertThat(subclasses).hasSize(4)
assertThat(subclasses).containsExactlyInAnyOrder(
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.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.