我有接口(interface) A,它有接口(interface) B 作为字段。当我执行 A 的实现(假设是creteA)时,我没有提供接口(interface) 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
}
最佳答案
您从父亲那里继承了一些东西,这一事实并不意味着您就是您的父亲。
此处数据类的使用有点令人困惑,因为您的代码无法使用它们进行编译。
这是代码工作的正确方式:
interface B
class ConcreteB : B
interface A {
var someField: B
}
class ConcreteA : A {
override var someField: B = // That's the interface
ConcreteB() // That's the implementation
}
关于java - 在kotlin中将接口(interface)定义为接口(interface)的属性并在接口(interface)实现中提供具体的实现是行不通的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57555797/