为什么'is'关键字仅适用于Kotlin中的开放类?

时间:2019-08-12 15:23:50

标签: kotlin

我的问题可能是菜鸟,但请帮助我。我不明白在Kotlin中不允许使用“ is”关键字的非开放类的目的是什么。

示例代码1

fun main(){
    val randomclassobject = RandomClass()
    println(randomclassobject is someRandomInterface)
}
open class RandomClass{
}
interface someRandomInterface{
    fun mustImplementThis()
}

上面的代码工作得很好

现在 示例代码2

fun main(){
    val randomclassobject = RandomClass()
    println(randomclassobject is someRandomInterface)
}
class RandomClass{
}
interface someRandomInterface{
    fun mustImplementThis()
}

没有打开关键字,它显示错误“ Error:(3,34)Kotlin:不兼容的类型:someRandomInterface和RandomClass”

为什么打开关键字真的很重要?

1 个答案:

答案 0 :(得分:6)

当你这样写的时候

class RandomClass {
}
interface SomeRandomInterface {
    fun mustImplementThis()
}

任何对象都不能同时是RandomClass SomeRandomInterface的实例,因为RandomClass本身并不实现SomeRandomInterface且它不能有任何实现它的子类,因为它不是开放的(默认情况下,除非添加open,否则不能扩展Kotlin类)。

由于编译器知道此检查不能返回true,因此将其标记为错误。其他大多数语言可能只会警告您该支票没有用,但Kotlin完全将其视为非法。

另一方面,当你写

open class RandomClass {
}
interface SomeRandomInterface {
    fun mustImplementThis()
}

即使类本身未实现该接口,也可以 具有实现该接口的子类,例如

open class RandomClass {
}
interface SomeRandomInterface {
    fun mustImplementThis()
}
class RandomSubClass : RandomClass(), SomeRandomInterface {
    fun mustImplementThis() {}
}

这意味着该检查可以返回true,因此在这种情况下,编译器允许这样做。