首页 文章

Kotlin在其他地方访问支持领域?

提问于
浏览
0

我发现它只能访问集合中的后备字段或get.Is有什么方法可以访问类中其他地方的后备字段?例如 .

var width:Int=0
get() {
    return field*10;
}
set(value) {
    field=value/10;
}

我想访问真正的 Value ,但不是多次10

当我使用c#时,没有字段关键字,所以总是需要声明一个新的变量来存储真实的数据 . 在前面的例子中,它会看起来像

private var _width=0;
var width:Int
get() {
    return _width*10;
}
set(value) {
    _width=value/10;
}

所以,如果我想在课堂上访问真正的 Value ,我可以访问_value . 但是在kotlin,如果没有这些详细的声明,有没有可能只是访问支持领域?

2 回答

  • 1

    Kotlin,您可以使用支持属性

    Backing Properties

    如果你想做一些不适合这种“隐式支持字段”方案的事情,你总是可以回到拥有支持属性:

    private var _table: Map<String, Int>? = null
    public val table: Map<String, Int>
        get() {
            if (_table == null) {
                _table = HashMap() // Type parameters are inferred
            }
            return _table ?: throw AssertionError("Set to null by another thread")
        }
    

    在所有方面,这与Java中的相同,因为对具有默认getter和setter的私有属性的访问进行了优化,因此不会引入任何函数调用开销 .

  • 2

    不 . 你的C#示例在Kotlin中运行正常,它被称为backing property .

相关问题