Kotlin : Public get private set var

Kotlin

Kotlin Problem Overview


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

Kotlin Solutions


Solution 1 - Kotlin

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

Solution 2 - Kotlin

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasper BluesView Question on Stackoverflow
Solution 1 - KotlinD3xterView Answer on Stackoverflow
Solution 2 - KotlinAndy JazzView Answer on Stackoverflow