alexey polusov alexey polusov - 4 months ago 45x
Android Question

Getters and Setters in Kotlin

guys. I'm new in Kotlin and I'm trying to figure out how to use getters and setters in Kotlin.
In java I need to write getters on my own(generate by ide) or use Annotations like @Getter in lombok, which was pretty simple.
Kotlin however has getters and setters by default.
But I can't understand how to use it.

I want to make it, lets say - similar to java:

private val isEmpty: String
get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.

So how getters work?


Getters and setters are auto-generated in Kotlin. If you write:

val isEmpty: String

It is equals to next Java code:

private final String isEmpty;

public String getIsEmpty() {
    return isEmpty;

In your case private access modifier is redundant - isEmpty is private by default and can be access only by getter. When you try to get your object isEmpty property you call get method in real. For more understanding of getters/setters in Kotlin: two code samples below are equals:

var someProperty: String = "defaultValue"


var someProperty: String = "defaultValue"
    get() = filed
    set(value) { field = value }

Also I want to notice that this in getter is not your property - it's class instance. If you want to get access to the field value in getter or setter you can use field reserved word for it:

val isEmpty: String
  get() = field.reversed()

If you want to have only get method in public access - you can write this code:

var isEmpty: String
    private set 

due to private modifier near set accessor you can set this value only in methods inside your object.