248

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

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185

2 Answers2

416
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

D3xter
  • 6,165
  • 1
  • 15
  • 13
27

Public getter, private setter

You can easily accomplish this using the following approach:

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

Look at this post for details.

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220