在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
}
}
我希望属性name
的setter是私有的,并且公开的getter,我该怎么办?
答案 0 :(得分:14)
解决方案是在构造函数之外创建一个属性并设置setter的可见性。
class Sample(var id: Int, name: String) {
var name: String = name
private set
}
<强>更新强>
他们在这里讨论它:https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640
答案 1 :(得分:1)
您可以尝试这样
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)
}