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

非 Y 不嫁゛ 提交于 2019-12-19 14:23:41

问题


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)
}


来源:https://stackoverflow.com/questions/44404969/in-kotlin-how-to-make-the-setter-of-properties-in-primary-constructor-private

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!