请参阅接口kotlin中定义的属性



伙计们,我正在学习kotlin。从…起https://kotlinlang.org/docs/interfaces.html#properties-在接口中,它说:

接口中声明的属性不能有后备字段,并且因此,在接口中声明的访问器不能引用它们。

(我认为引用句子末尾的代词"they"应该指"属性",而不是"字段"。(

但是,以下代码是有效的。看来我们可以参考性质。为什么print(prop)高亮显示为红色?

interface MyInterface {
val prop: Int // abstract
val propertyWithImplementation: String
get() = "foo"
fun foo() {
print(prop) // this is highlighted red but it works. what's does the author want to say?
}
}
class Child : MyInterface {
override val prop: Int = 29
}
fun main() {
val c = Child()
c.foo()
}

此外,我注意到在上面的示例中,foo不是访问器。所以我尝试了下面的例子,它也起作用:

interface User {
val email: String
val nickname: String
get() = email.substringBefore('@') // aren't we referring to a property in accessor? why does this work then?
}

那么作者想在这里说什么呢?什么是";他们";提到

"他们"在这个句子中的意思是";字段";。

属性基本上是一个getter(setter(,它可以有选择地由一个字段支持。由于技术原因,接口不能包含字段,因此接口中的属性必须是";"无场";。属性必须是抽象的,或者其实现只能使用例如其他属性/函数,但不能直接存储/读取任何数据。请注意,引用其他属性并不会破坏上述规则,因为正如我所说,属性主要是getter/setter,而不是字段。

print(prop)高亮显示为红色,因为。。。好吧,这就是自动荧光笔给它上色的方式…:-(

最新更新