Jasper Blues
Jasper Blues

Reputation: 28786

Kotlin : Public get private set var

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

Upvotes: 267

Views: 98427

Answers (2)

D3xter
D3xter

Reputation: 6465

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

However, in case of constructor(s), if possible use val instead of var, otherwise, Kotlin constructors do NOT support "private set", and you would need to create separate property, and set that through constructor:

class MyClass(private var myConstructorArg: String) {
    var myPropery: String = myConstructorArg; private set
}

Upvotes: 438

Andy Jazz
Andy Jazz

Reputation: 58553

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.

Upvotes: 30

Related Questions