Kotlin : Public get private set var

后端 未结 3 356
借酒劲吻你
借酒劲吻你 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:56
    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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 03:02

    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.

    0 讨论(0)
提交回复
热议问题