Getters/setters

In general property in Kotlin consits from backfield, that hold data in memory, and getter/setter methods. Suppose property has name result, then Kotlin will generate methods getResult() and setResult(v).

On JVM: access to private properties with default getters and setters is optimized to avoid function call overhead.

You can change visibility of getter/setter method. For example, make setter private means, that user can read value from property, but can not modify.

var prop: String = ""
    private set

You can override property with new getter/setter methods.

open class Cls{
    open val parentProp = ""
}


class MyClass: Cls() {
    override val parentProp: String
        get() = super.parentProp
}

It is possible override val property to the var property.

interface Data{
    val data: Any
}

class MutableData: Data{
    // if necessary specify getter/setter
    override var data: Any = Unit
}

You can inline property or getter/setter.

enum class TaskState {
    // ...
    inline val isSuccess
        get() = this == SUCCESS
}

class Query{
    // ...
    val resultState: TaskState
        inline get() = queryState.resultState
}

The field variable within getter/setter refers to the default backfield of property. You can define custom backfield.

var prop1: String = ""
    set(v) {
        //... do something
        field = v
    }

// custom backfield for myProp2 property
private var _myProp = "" 

var myProp: String
    get() {
        // ... do something
        return _myProp
    }
    set(v) {
        // ... do something
        _myProp = v
    }