在kotlin中,如何使主构造函数中的属性setter成为私有?

Jos*_*Yan 10 constructor kotlin

在kotlin中,如何使主构造函数中的属性setter成为私有?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望属性的setter name是私有的,并且公开的getter,我该怎么办?

Mih*_*x64 20

解决方案是在构造函数之外创建属性并设置setter的可见性.

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

    var name: String = name
        private set

}
Run Code Online (Sandbox Code Playgroud)

更新:
他们在这里讨论:https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640