Sobes.tech
Junior — Middle

Explain what closed classes are in Kotlin and how they are used.

sobes.tech AI

Answer from AI

In Kotlin, there is no specific concept of "closed classes" as a separate type, but there is a similar concept — sealed classes.

A sealed class restricts the inheritance hierarchy: all subclasses of such a class must be declared in the same file. This allows the compiler to know all possible subclasses and use this, for example, in when expressions without needing to write an else branch.

Using sealed classes is convenient for modeling a limited set of options, such as states or events.

Example:

sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val error: Throwable) : Result()
}

fun handleResult(result: Result) {
    when(result) {
        is Result.Success -> println("Data: ${result.data}")
        is Result.Error -> println("Error: ${result.error.message}")
    }
}

If "closed classes" refers to classes with the private or internal modifier, then these are classes with restricted visibility: private — visible only within the file, internal — within the module.

Explain what closed classes are in Kotlin and how… - sobes.tech