Kotlin中的吸气剂和吸气剂 [英] Getters and Setters in Kotlin
问题描述
例如,在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.
但是,科特林默认具有 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.
那么吸气剂如何工作?
So how do getters work?
推荐答案
字母和设置者是在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中的吸气剂和吸气剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!