Kotlin Sealed Classes and Sealed Interfaces
A sealed class represents a restricted class hierarchy: all possible types of a value are fully determined at compile time.
Precisely because the subclasses are a known, finite set, a when expression can pass the exhaustiveness check without an else.
It's often used to model state machines, interface return results, and event types—cases where "there are only these few possibilities".
Defining a sealed class
A class modified with sealed is a sealed class; it is abstract itself and can't be instantiated directly.
A sealed class's constructor is protected by default, so only its subclasses can inherit from it.
Example
// File: RunoobResult.kt
sealed
class
RunoobResult
// Subclasses and the sealed class are written in the same file
data
class
Success
(
val data
:
String
)
:
RunoobResult
(
)
data
class
Failure
(
val message
:
String
)
:
RunoobResult
(
)
object Loading
:
RunoobResult
(
)
fun main
(
)
{
val result
:
RunoobResult
=
Success
(
"www.runoob.com"
)
println
(
result
)
// RunoobResult() // Compile error: a sealed class can't be instantiated directly
}
Success(data=www.runoob.com)
Subclasses can be normal classes, data classes, or objects; there's no restriction on their form.
This also means each subclass can carry completely different data, which is where sealed classes are more flexible than enums.
Location of subclasses
The most commonly misremembered rule about sealed classes is where subclasses must be placed.
Kotlin 1.0 required all subclasses to be nested inside the sealed class; this restriction was removed long ago.
Since Kotlin 1.1 (KEEP-29), subclasses only need to be in the same file as the sealed class; they needn't be nested.
Since Kotlin 1.5, this is further relaxed to any file in the same module and package.
Example
// File: RunoobResult.kt
// Recommended: subclasses and the sealed class in the same file, declared side by side, no nesting needed
sealed
class
RunoobResult
class
Success
(
val data
:
String
)
:
RunoobResult
(
)
class
Failure
(
val message
:
String
)
:
RunoobResult
(
)
// The following "must be nested" style was an old Kotlin 1.0 restriction and is no longer needed
sealed
class
OldStyleResult
{
class
Success
(
val data
:
String
)
:
OldStyleResult
(
)
class
Failure
(
val message
:
String
)
:
OldStyleResult
(
)
}
fun main
(
)
{
val a
:
RunoobResult
=
Success
(
"runoob"
)
val b
:
OldStyleResult
=
OldStyleResult.
Success
(
"RUNOOB"
)
println
(
a.
javaClass
.
simpleName
)
println
(
b.
javaClass
.
simpleName
)
}
Success
Success
Note:Don't treat "subclasses must be nested in the sealed class" as a current rule. Since Kotlin 1.1 the same file is enough, and since Kotlin 1.5 any file in the same module and package is fine. Nesting subclasses is still legal, but that's a style choice, not a syntax requirement.
Sealed interfaces (since Kotlin 1.4)
Since Kotlin 1.4 (KT-44016), interfaces can also be modified with sealed.
The rules for sealed interfaces are basically the same as for sealed classes: direct subclasses must be declared in the same file.
Example
// File: RunoobEvent.kt
// Since Kotlin 1.4, an interface can also be declared sealed
sealed
interface
RunoobEvent
data
class
Click
(
val x
:
Int, val y
:
Int
)
:
RunoobEvent
data
class
Scroll
(
val delta
:
Int
)
:
RunoobEvent
data object Refresh
:
RunoobEvent
// data object requires Kotlin 1.9 or later
fun handle
(
event
:
RunoobEvent
)
:
String
=
when
(
event
)
{
is Click
->
"Click coordinates: (${event.x}, ${event.y})"
is Scroll
->
"Scroll: ${event.delta}"
Refresh
->
"Refresh"
}
fun main
(
)
{
println
(
handle
(
Click
(
10
,
20
)
)
)
println
(
handle
(
Scroll
(
5
)
)
)
println
(
handle
(
Refresh
)
)
}
点击坐标:(10, 20)
滚动:-5
刷新
Sealed interfaces have one advantage over sealed classes: a class can implement multiple sealed interfaces.
Example
sealed
interface
RunoobClickable
sealed
interface
RunoobHoverable
// A class can implement multiple sealed interfaces at once
class
RunoobButton
:
RunoobClickable, RunoobHoverable
fun main
(
)
{
val button
=
RunoobButton
(
)
println
(
button is RunoobClickable
)
println
(
button is RunoobHoverable
)
}
true
true
If you just need a closed class hierarchy without state inheritance, prefer a sealed interface.
Working with when exhaustiveness
The most valuable use of sealed classes is making missing when branches surface at compile time.
When when is used as an expression, as long as all subclasses are covered you don't need an else.
Example
sealed
class
RunoobState
{
object Idle
:
RunoobState
(
)
object Running
:
RunoobState
(
)
data
class
Error
(
val code
:
Int
)
:
RunoobState
(
)
}
// As an expression: you must cover all branches; missing any one fails to compile
fun label
(
state
:
RunoobState
)
:
String
=
when
(
state
)
{
RunoobState.
Idle
->
"Idle"
RunoobState.
Running
->
"Running"
is RunoobState.
Error
->
"Error code ${state.code}"
}
fun main
(
)
{
println
(
label
(
RunoobState.
Idle
)
)
println
(
label
(
RunoobState.
Running
)
)
println
(
label
(
RunoobState.
Error
(
404
)
)
)
}
空闲
运行中
错误码 404
When you later add a new subclass to a sealed class, every when that doesn't handle it immediately reports an error, and the compiler helps you find all the places to modify.
Since Kotlin 1.6, a when statement whose subject is a sealed type warns if branches aren't exhaustive; since Kotlin 1.7 this has become an error.
In other words, whether when is an expression or a statement, you shouldn't omit branches.
Sealed classes vs enums
Both work with exhaustiveness checks, but their applicable scenarios differ noticeably.
| Comparison Item | sealed class / sealed interface | enum class |
|---|---|---|
| Number of instances | Each subclass can have any number of instances | Each constant has only one instance globally |
| Carrying data | Different subclasses can carry completely different properties | All constants share the same set of properties |
| Subclass form | class, data class, or object are all allowed | Only the enum constants themselves |
| Mutable state | Yes, each instance is independent. | Constants are singletons, not suitable for storing mutable state. |
| when exhaustiveness | Supported | Supported |
| Typical scenario | State machines, request results, event types | Days of the week, colors, fixed options |
In short: enums express "a fixed set of values", while sealed classes express "a fixed set of cases".
Example
// Enum: all constants share the same set of properties and cannot express "each branch carrying different data"
enum
class
RunoobStatus
(
val code
:
Int
)
{
OK
(
200
)
, NOT_FOUND
(
404
)
, TIMEOUT
(
0
)
}
// Sealed class: each subclass can carry its own data
sealed
class
RunoobResponse
{
data
class
Ok
(
val body
:
String
)
:
RunoobResponse
(
)
data
class
NotFound
(
val path
:
String
)
:
RunoobResponse
(
)
data object Timeout
:
RunoobResponse
(
)
}
fun describe
(
response
:
RunoobResponse
)
:
String
=
when
(
response
)
{
is RunoobResponse.
Ok
->
"Returned content: ${response.body}"
is RunoobResponse.
NotFound
->
"Path not found: ${response.path}"
RunoobResponse.
Timeout
->
"Request timed out"
}
fun main
(
)
{
println
(
RunoobStatus.
OK
.
code
)
println
(
describe
(
RunoobResponse.
Ok
(
"RUNOOB"
)
)
)
println
(
describe
(
RunoobResponse.
NotFound
(
"/runoob"
)
)
)
println
(
describe
(
RunoobResponse.
Timeout
)
)
}
200
返回内容:RUNOOB
找不到路径:/runoob
请求超时
Common questions
Here are a few common issues you may run into when using sealed classes.
Can a sealed class be instantiated directly?
No. A sealed class is abstract itself; objects must be created through its subclasses.
A subclass declared with object can be used directly as an instance.
Can subclasses of a sealed class have further subclasses?
Yes. A sealed class can extend another sealed class; direct subclasses must still satisfy the location requirement.
Indirect subclasses can be placed in other files as long as their own direct parent follows the rules.
When should you use a sealed interface instead of a sealed class?
When you don't need shared state or inherited implementation, just a closed set of tags, a sealed interface is lighter.
When you need to provide common implementation or common properties to subclasses, a sealed class is more appropriate.
Why don't you need else in when?
Because the set of subclasses of a sealed class is known at compile time, the compiler can tell whether all cases are covered.
If you add else manually, it will hide omissions when new subclasses are added later.