Better

业精于勤荒于嬉

Idiomatic Kotlin:sealed class

Better's Avatar 2019-05-26 Kotlin

  1. 1. define and use
  2. 2. bummock
  3. 3. 参考

sealed是 kotlin 中的一个关键字,用于限制某个类的继承层次。看起来更清晰。

define and use

1
2
3
4
5
sealed class NaviBar(private val name: String) {
class RedNaviBar : NaviBar("red")
}

class GreedNaviBar : NaviBar("greed")

bummock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public abstract class NaviBar {
private final String name;

private NaviBar(String name) {
this.name = name;
}

// $FF: synthetic method
public NaviBar(String name, DefaultConstructorMarker $constructor_marker) {
this(name);
}

public static final class RedNaviBar extends NaviBar {
public RedNaviBar() {
super("red", (DefaultConstructorMarker)null);
}
}
}

public final class GreedNaviBar extends NaviBar {
public GreedNaviBar() {
super("greed", (DefaultConstructorMarker)null);
}
}

sealed标记的类是一个抽象类,并且构造函数是一个private的,所以并不能从外界访问,只能写在一个文件中
同时生成了一个带DefaultConstructorMarker参数的构造方法,子类通过这个方法来初始化父类。不过这个类也是受保护的的类kotlin.jvm.internal

sealed有一个好处是在编译期间,就可以知道所有的子类。在使用when表达式的时候,可以验证是否覆盖了所有条件。

1
2
3
4
5
6
7
public fun transNaviBar(naviBar: NaviBar): String {
return when (naviBar) {
is NaviBar.RedNaviBar -> {
"is Red"
}
}
}

比如上面这样不写else,会报错

1
'when' expression must be exhaustive, add necessary 'is Agility' branch or 'else' branch instead

参考

kotlinDoc-sealed
Idiomatic Kotlin: Sealed Classes

This article was last updated on days ago, and the information described in the article may have changed.