I'm very new to Kotlin and trying to migrate one project from Java to it. I'm a bit confused with Kotlin's properties and getters/setters for them along with visibility scope.
What I want to achieve is:
public class Foo {
private int number;
public int getNumber() {
return number;
}
public void increment() {
number++;
}
}
So basically I need to create a class with a private property number
. This property should be accessible by the public getter, but it shouldn't have a setter. Also, this property should be internally mutable, so that its value can be changed using some method like increment()
.
As far as I understand, I can't declare it as val
, because in that case, it would be completely immutable, even from within the instance of a class, so I can't increment it. Looks like it should be var
. But then I don't see an option to make the property itself be private
and the getter for this property to be public
, because it seems that properties and their getters/setters should have the same visibility scope...
If you use Intellij you could just paste your code into a Kotlin class and would have received the following:
class Foo {
var number: Int = 0
private set
fun increment() {
number++
}
}
And this basically is also the answer to your problem...
private set
tells that the setter is only privately visible. So you can access it within Foo
, but not from outside. The 0
you set explicitly (in contrast to Java). Then: by default the property and functions are public
.
Check also the Kotlin reference regarding properties (specifically getter/setter)