【发布时间】:2019-12-24 14:49:33
【问题描述】:
我有接口 A,其中接口 B 作为字段。当我执行 A 的实现时,假设具体 A,而不是提供接口 B,而是提供 B 的实现,编译器会抛出一个错误。我不明白为什么,因为在 Kotlin 中有继承,我认为这应该可行。顺便说一下,我用数据类试过这个。
interface B {
....
}
data class concreteB : B {
.....
}
interface A {
var someField: B
}
data class concreteA : A {
//The error happens here, compiler says it's not type of overridden
override var someField: concreteB
}
【问题讨论】:
-
我在 Slack 上和 Kotlin 的人交谈过,解释是 LSP(Liskov 替换原则)参考:stackoverflow.com/questions/56860/…。似乎在 Kotlin 中不可能实现它,但我可能是错的。
标签: java inheritance kotlin interface