WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Intermediate · question 22 of 100

What are sealed classes in Kotlin? How do they differ from regular classes or interfaces?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, a ‘sealed class‘ is a class that can be subclassed only within its own file. It is a restriction imposed by the Kotlin compiler that prevents other files from creating subclasses of the sealed class. This concept is similar to an ‘enum‘ in Java, but ‘sealed classes‘ can have multiple instances with different properties and behavior.

Here is an example of a ‘sealed class‘:

sealed class Expr

data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()

In this example, ‘Expr‘ is a ‘sealed class‘. It has three subclasses: ‘Const‘, ‘Sum‘, and ‘NotANumber‘. The ‘Const‘ and ‘Sum‘ classes are ‘data classes‘ that store a value and expressions respectively. The ‘NotANumber‘ class is an ‘object‘ expression that represents the absence of a value.

‘Sealed classes‘ are similar to ‘enums‘, but they can have more than one instance, and each instance can have different properties and behaviors. ‘Sealed classes‘ are more powerful than ‘enums‘ because they represent a hierarchy of classes with different behavior that might be needed to implement specific functionality. Besides, ‘sealed classes‘ are more flexible and can be used in the same way as other classes.

‘Sealed classes‘ can contain abstract methods and properties. They can be used in ‘when‘ expressions, which are similar to a ‘switch‘ statement in Java. For example:

fun eval(expr: Expr): Double = when (expr) {
    is Const -> expr.number
    is Sum -> eval(expr.e1) + eval(expr.e2)
    NotANumber -> Double.NaN
    // the `else` clause is not required because all subclasses of `Expr` are covered in the `when` statement
}

In this example, ‘when‘ is used to determine the type of the ‘expr‘ parameter and execute different logic for each type. ‘NotANumber‘ is used to represent an unknown value, similar to ‘NaN‘ in Java.

In conclusion, ‘sealed classes‘ are an important construct in Kotlin that can be used to represent a hierarchy of classes with different behavior. They are more powerful than ‘enums‘ because they can have more than one instance and each instance can have different properties and behaviors. ‘Sealed classes‘ can also contain abstract methods and properties and can be used in ‘when‘ statements.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics