Kotlin : Public get private set var

后端 未结 3 378
借酒劲吻你
借酒劲吻你 2020-12-03 02:13

What is the correct way to define a var in kotlin that has a public getter and private (only internally modifiable) setter?

3条回答
  •  执念已碎
    2020-12-03 02:59

    You can easily do it using the following approach:

    var atmosphericPressure: Double = 760.0
        get() = field
        private set(value) { 
            field = value 
        }
    

    Look at this story on Medium: Property, Getter and Setter in Kotlin.

提交回复
热议问题