在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 - 如何在Kotlin中跳过定义的getter或setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61459289/