【发布时间】:2021-06-13 23:21:24
【问题描述】:
伙计们,我正在学习 kotlin。来自https://kotlinlang.org/docs/interfaces.html#properties-in-interfaces 它说:
接口中声明的属性不能有支持字段,并且 因此在接口中声明的访问器不能引用它们。
(我认为引用句末的代词“them”应该指“properties”而不是“fields”。)
但是下面的代码可以工作。看来我们可以参考属性。为什么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?
}
那么作者在这里想表达什么? “他们”指的是什么?
【问题讨论】:
-
基于这篇文章我认为它确实引用了字段:baeldung.com/kotlin/backing-fields
标签: kotlin