Kotlin only getter pulblic, private setter [duplic

2019-06-24 00:34发布

问题:

This question already has an answer here:

  • Kotlin : Public get private set var 2 answers

I just started using Kotlin and found getters and setters very useful.

I am wondering if Kotlin provides only getters public.

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?

回答1:

You can define the accessor without defining its body:

var score: Int = 0
    private set

In this case the setter is private.

From the docs:

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


回答2:

You can use this syntax :

var setterVisibility: String = "abc" // Initializer required, not a nullable type
    private set // the setter is private and has the default implementation

Please refer to the official here

Also it's a doublon with this question



标签: kotlin