例如,在Java中,我可以自己编写getter(由IDE生成)或者在lombok中使用@Getter之类的注释 - 这非常简单.
然而,Kotlin 默认拥有getter和setter.但我无法理解如何使用它们.
我想说,就像Java一样:
private val isEmpty: String
get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.
Run Code Online (Sandbox Code Playgroud)
那么吸气剂如何工作?
我刚开始使用Kotlin,发现getter和setter非常有用.
我想知道Kotlin是否只提供吸气剂.
它不应该是val
因为它的价值可以通过它的类来改变.
我为实现这一目标所做的工作如下.
private var _score: Int=0
val score: Int = _score
get() = _score
Run Code Online (Sandbox Code Playgroud)
使用这种方式,我必须声明两个变量.
有没有更好的方法来公开吸气剂?