Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin only getter pulblic, private setter [duplicate]

Tags:

kotlin

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?

like image 775
Hyun I Kim Avatar asked Feb 26 '18 23:02

Hyun I Kim


2 Answers

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

like image 22
Bruno Avatar answered Nov 01 '22 00:11

Bruno


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
like image 171
acdcjunior Avatar answered Nov 01 '22 00:11

acdcjunior