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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With