210

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

Jasper Blues
  • 27,820
  • 20
  • 98
  • 179

2 Answers2

334
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
  • 5,305
  • 1
  • 14
  • 12
10

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.

Andy Jazz
  • 36,357
  • 13
  • 107
  • 175