如果我在Kotlin中有一个接口:
我可以这样来实现它:
然而,如果我要使用类似这样的Java接口:
interface KotlinInterface {
val id: String
}
我可以这样来实现它:
class MyClass : KotlinInterface {
override val id: String = "id"
}
然而,如果我要使用类似这样的Java接口:
public interface JavaInterface {
String id = "id";
}
我无法以类似的方式覆盖 id
类变量:
class MyClass : JavaInterface {
override val myId: String = JavaInterface.id //linter says: 'myId' overrides nothing
}
尽管id
有预定义的值,但我无法在其他地方使用它:
class MyClass : JavaInterface {
val myArray: Array<String> = arrayOf(id) // linter would say that id is not defined rather than recognising it as the string “id”
}
看起来我必须这样使用它:
class MyClass {
val id: String = JavaInterface.id
val myArray: Array<String> = arrayOf(id)
}
能有人解释一下这个行为差异并指出我可能理解错误的部分吗?