13

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?

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
Hyun I Kim
  • 589
  • 1
  • 3
  • 14

2 Answers2

28

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
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
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

Bruno
  • 178
  • 1
  • 2
  • 6