如何跳过 Kotlin 中定义的 getter 或 setter
How to skip defined getters or setters in Kotlin
在 java 中,您可以执行以下操作:
public class Foo {
private String bar = "text";
public void method() {
// direct access (no logic)
System.out.println(this.bar);
}
// only if you access the object from the outside
// you are forced to use the getter with some logic in it
public String getBar() {
System.out.println(this.bar);
return this.bar;
}
}
但是,如果您在 Kotlin 中使用逻辑定义 getter 或 setter,则在访问该字段时,您必须始终执行此逻辑:
class Foo {
var bar: String = "text"
get() {
println(field)
return field
}
private set
fun method() {
// this also executes the getter
// Is it possible to skip the getter
// and directly access the field?
println(this.bar)
}
}
有没有比在 Kotlin 中创建自己的 fun getBar()
更好的方法来访问字段而不执行 getter 或 setter 逻辑?
无法跳过 getter 或 setter,它们旨在阻止 属性.
的直接访问
你可以做的是对同一个值进行多重引用(假引用):
private var _bar: String = "text"
var bar
get() {
// some operations intercepting the getter
return _bar
}
// direct access
_bar
// intercepted access public field
bar
在 Kotlin 中,支持字段(在您的情况下为私有变量)未按设计公开。这里解释了一些例外情况:https://kotlinlang.org/docs/reference/properties.html#backing-fields
所有对 val
和 var
的访问都通过隐式 getters 和 setters 发生。 val
使用 getter() 解析为 属性,而 var
使用 getter 和 [=22= 解析为 属性 ]: https://kotlinlang.org/docs/reference/properties.html#properties-and-fields
在 java 中,您可以执行以下操作:
public class Foo {
private String bar = "text";
public void method() {
// direct access (no logic)
System.out.println(this.bar);
}
// only if you access the object from the outside
// you are forced to use the getter with some logic in it
public String getBar() {
System.out.println(this.bar);
return this.bar;
}
}
但是,如果您在 Kotlin 中使用逻辑定义 getter 或 setter,则在访问该字段时,您必须始终执行此逻辑:
class Foo {
var bar: String = "text"
get() {
println(field)
return field
}
private set
fun method() {
// this also executes the getter
// Is it possible to skip the getter
// and directly access the field?
println(this.bar)
}
}
有没有比在 Kotlin 中创建自己的 fun getBar()
更好的方法来访问字段而不执行 getter 或 setter 逻辑?
无法跳过 getter 或 setter,它们旨在阻止 属性.
的直接访问你可以做的是对同一个值进行多重引用(假引用):
private var _bar: String = "text"
var bar
get() {
// some operations intercepting the getter
return _bar
}
// direct access
_bar
// intercepted access public field
bar
在 Kotlin 中,支持字段(在您的情况下为私有变量)未按设计公开。这里解释了一些例外情况:https://kotlinlang.org/docs/reference/properties.html#backing-fields
所有对 val
和 var
的访问都通过隐式 getters 和 setters 发生。 val
使用 getter() 解析为 属性,而 var
使用 getter 和 [=22= 解析为 属性 ]: https://kotlinlang.org/docs/reference/properties.html#properties-and-fields