【问题标题】:refer to property defined in interface, kotlin引用接口中定义的属性,kotlin
【发布时间】: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?
}

那么作者在这里想表达什么? “他们”指的是什么?

【问题讨论】:

标签: kotlin


【解决方案1】:

这句话中的“Them”表示“领域”。

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

print(prop) 突出显示为红色,因为...嗯,这就是自动荧光笔的颜色... :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多