例如,在 Java 中,我可以自己编写 getter(由 IDE 生成)或在 lombok 中使用诸如 @Getter 之类的注解——这非常简单.
In Java, for example, I can write getters on my own (generated by IDE) or use Annotations like @Getter in lombok - which was pretty simple.
Kotlin 具有默认情况下的getter 和setter.但我不明白如何使用它们.
Kotlin however has getters and setters by default. But I can't understand how to use them.
我想实现,比如说 - 类似于 Java:
I want to make it, lets say - similar to Java:
private val isEmpty: String get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.那么getter是如何工作的呢?
So how do getters work?
推荐答案Getter 和 setter 在 Kotlin 中自动生成.如果你写:
Getters and setters are auto-generated in Kotlin. If you write:
val isEmpty: Boolean相当于下面的Java代码:
It is equal to the following Java code:
private final Boolean isEmpty; public Boolean isEmpty() { return isEmpty; }在您的情况下,私有访问修饰符是多余的 - isEmpty 默认是私有的,只能由 getter 访问.当您尝试获取对象的 isEmpty 属性时,您实际上会调用 get 方法.为了更深入地了解 Kotlin 中的 getter/setter:下面的两个代码示例是相等的:
In your case the private access modifier is redundant - isEmpty is private by default and can be accessed only by a getter. When you try to get your object's isEmpty property you call the get method in real. For more understanding of getters/setters in Kotlin: the two code samples below are equal:
var someProperty: String = "defaultValue"和
var someProperty: String = "defaultValue" get() = field set(value) { field = value }我还想指出,getter 中的 this 不是您的财产 - 它是类实例.如果你想在 getter 或 setter 中访问字段的值,你可以使用保留字 field :
Also I want to point out that this in a getter is not your property - it's the class instance. If you want to get access to the field's value in a getter or setter you can use the reserved word field for it:
val isEmpty: Boolean get() = field如果您只想在公共访问中使用 get 方法 - 您可以编写以下代码:
If you only want to have a get method in public access - you can write this code:
var isEmpty: Boolean private set由于靠近 set 访问器的 private 修饰符,您只能在对象内部的方法中设置此值.
due to the private modifier near the set accessor you can set this value only in methods inside your object.
更多推荐
Kotlin 中的 Getter 和 Setter
发布评论