Kotlin Only Getter公用,私人二传手 [英] Kotlin only getter pulblic, private setter
问题描述
我刚开始使用Kotlin,发现吸气剂和塞特剂非常有用.
I just started using Kotlin and found getters and setters very useful.
我想知道科特林是否只公开提供吸气剂.
I am wondering if Kotlin provides only getters public.
它不应为val
,因为它的值可以由其类更改.
It should not be val
because it's value can be changed by it's class.
我为实现这一目标所做的工作如下.
What I've done to achieve this is as follows.
private var _score: Int=0
val score: Int = _score
get() = _score
使用这种方式,我必须声明两个变量.
Using this way, I have to declare two variables.
有什么更好的方法只公开获取者吗?
Is there any better way to only make getters public?
推荐答案
您可以定义访问器而无需定义其主体:
You can define the accessor without defining its body:
var score: Int = 0
private set
在这种情况下,设置器是私有的.
In this case the setter is private.
来自文档:
如果您需要更改访问器的可见性或对其进行注释, 但无需更改默认实现,您可以定义 没有定义其主体的访问器:
If you need to change the visibility of an accessor or to annotate it, but don't need to change the default implementation, you can define the accessor without defining its body:
var setterVisibility: String = "abc"
private set // the setter is private and has the default implementation
这篇关于Kotlin Only Getter公用,私人二传手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!