constructorkotlin

In kotlin, how to make the setter of properties in primary constructor private?


In kotlin, how to make the setter of properties in primary constructor private?

class City(val id: String, var name: String, var description: String = "") {

    fun update(name: String, description: String? = "") {
        this.name = name
        this.description = description ?: this.description
    }
}

I want the setter of properties name to be private, and the getter of it public, how can I do?


Solution

  • The solution is to create a property outside of constructor and set setter's visibility.

    class Sample(var id: Int, name: String) {
    
        var name: String = name
            private set
    
    }
    

    Update:
    They're discussing it here: https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640