What is the correct way to define a var in kotlin that has a public getter and private (only internally modifiable) setter?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
var setterVisibility: String = "abc" // Initializer required, not a nullable type
private set // the setter is private and has the default implementation
See: Properties Getter and Setter
回答2:
You can easily do it using the following approach:
var atmosphericPressure: Double = 760.0
get() = field
private set(value) {
field = value
}
Look at this post on Medium: Property, Getter and Setter in Kotlin.
Hope this helps.
回答3:
var name : String = "Peter"
private set
By default all properties and functions are public in Kotlin. Hence the setter has to be explicitly declared private while the getter is public by default.