Kotlin密封类-为什么编译器不检查所有子类型?

时间:2019-01-23 19:29:12

标签: kotlin sealed-class

使用sealed classes时,编译器仅检查同一文件中的子类型。

密封类的最大卖点之一是使用when表达式时的详尽检查。那为什么不执行呢?

在1个文件中,我有:

class C : B()

在另一个文件中,我有:

sealed class A

open class B : A()

fun switch(input: A) =
    when(input) {
        is B -> Unit
//        is C -> Unit - I expect a compiler error since this is a subtype and it's commented out
    }

1 个答案:

答案 0 :(得分:0)

作为Eugene Petrenko commented一样,编译器所需的is B情况涵盖了B的所有子类。

相关问题