What are sealed classes in Kotlin?

In KotlinKotlin is an open-source, modern programming language that is concise, expressive, and interoperable with Java., a sealed class is a type of class that restrict the inheritance of a class to a fixed number of classes. This means that any class outside of the declared hierarchy of classes cannot extend the sealed class. In Kotlin development, combining sealed classes with when expression is a popular approach to restricting object types.

Syntax

The syntax for declaring a sealed class in Kotlin is as follows:

sealed class MySealedClass {
// Members of the sealed class
}

Code example

// Creating a sealed class, Colour, and three subclasses, Red, Green, and Blue, each with a shade property.
sealed class Colour {
class Red(val shade: String) : Colour() // SubClass 1
class Green(val shade: String) : Colour() // SubClass 2
class Blue(val shade: String) : Colour() // SubClass 3
}
fun main() {
// Creating three instances of the Colour class: red, green, and blue.
val red = Colour.Red("dark")
val green = Colour.Green("light")
val blue = Colour.Blue("medium")
val colours = listOf(red, green, blue)
colours.forEach { colour ->
val message = when (colour) { // assigning a message to a variable based on the colour's type and its shade property.
is Colour.Red -> "The shade of the red colour is ${colour.shade}."
is Colour.Green -> "The shade of the green colour is ${colour.shade}."
is Colour.Blue -> "The shade of the blue colour is ${colour.shade}."
}
println(message) // printing the message for each colour.
}
}

Code explanation

Lines 1–5: We define a sealed class Colour with three subclasses: Red, Green, and Blue. Each subclass has a property named shade.

Lines 8–10: We create three instances of the Colour class (red, green, and blue) using the Colour.Subclass(value) method to create each instance, where the Subclass is one of the three subclasses (Red, Green, or Blue) and value is the value that we want to assign to the shade property.

Line 12: We create a list named colours containing the three instances of the Colour class.

Lines 14–19: We use a forEach loop to iterate over each color in the colours list. We use a when expression to determine the type of each color (Red, Green, or Blue) and assign a message to the message variable based on the type of color and its shade property.

Conclusion

Sealed classes in Kotlin are a powerful language feature that can be used to restrict the inheritance of a class to a fixed number of classes. They are often used with when expressions to restrict the types of objects that can be used in the when expression.

Unlock your potential: Kotlin series, all in one place!

To continue your exploration of Kotlin, check out our series of Answers below:

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved