In kotlin, how to make the setter of properties in

2020-04-02 07:42发布

问题:

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?

回答1:

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



回答2:

You can try like this

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

    // Backing field
    var _name: String = ""
        get() = name
        private set

}

fun main(args: Array<String>) {
     println("Hello World")

     val sample = Sample(1, "hello")
    //    println(sample.name); It's not possible
    println(sample._name)
}