在Kotlin中,如何将主要构造函数中的属性的setter设为私有? [英] In kotlin, how to make the setter of properties in primary constructor private?
本文介绍了在Kotlin中,如何将主要构造函数中的属性的setter设为私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Kotlin中,如何将主要构造函数中的属性的设置方法设为私有?
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
}
}
我希望属性name
的设置方法是私有的,而属性的获取方法是公开的,我该怎么办?
I want the setter of properties name
to be private, and the getter of it public, how can I do?
推荐答案
解决方案是在构造函数之外创建属性并设置setter的可见性.
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
}
更新:
他们在这里进行讨论: https://describe.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640
Update:
They're discussing it here: https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640
这篇关于在Kotlin中,如何将主要构造函数中的属性的setter设为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文