TExcelTAD
Home › Kotlin › Kotlin Properties

Kotlin Properties

In Java you write private fields plus getX()/setX() methods. In Kotlin a property is both at once: obj.name looks like a field access but actually calls a getter (and obj.name = x calls a setter). You can customise these accessors, compute values on the fly and delay initialisation.

Custom getters

A property with a custom get() is computed every time it's read — no value is stored:

kotlin · try it yourself
class Rectangle(val width: Int, val height: Int) {
    val area: Int
        get() = width * height
    val isSquare get() = width == height
}

fun main() {
    val r = Rectangle(3, 4)
    println("area=${r.area} square=${r.isSquare}")
}
area=12 square=false

Custom setters and field

A custom set(value) runs whenever the property is assigned. Inside accessors, the keyword field refers to the stored value (the backing field):

kotlin · try it yourself
class Thermostat {
    var target: Int = 20
        set(value) {
            field = value.coerceIn(10, 30)
            println("Target set to $field")
        }
}

fun main() {
    val t = Thermostat()
    t.target = 24
    t.target = 45
    t.target = -3
    println("Final: ${t.target}")
}
Target set to 24
Target set to 30
Target set to 10
Final: 10

Note: Writing target = value inside the setter would call the setter again — infinite recursion. Always assign to field.

Getter vs. initializer

These two look similar but behave differently:

kotlin · try it yourself
class Clock(var hour: Int) {
    val label1 = "Hour $hour"            // computed once, at construction
    val label2 get() = "Hour $hour"      // computed on every read
}

fun main() {
    val c = Clock(9)
    c.hour = 17
    println(c.label1)
    println(c.label2)
}
Hour 9
Hour 17

lateinit

Non-null properties normally need a value at construction. Sometimes the value only becomes available later — e.g. set by a framework, a test setup or an onCreate method in Android. lateinit var promises "I'll assign this before using it":

kotlin · try it yourself
class Screen {
    lateinit var title: String

    fun setup(name: String) {
        title = name.uppercase()
    }

    fun show() = if (::title.isInitialized) "Showing $title" else "Not set up yet"
}

fun main() {
    val s = Screen()
    println(s.show())
    s.setup("settings")
    println(s.show())
}
Not set up yet
Showing SETTINGS

Reading a lateinit property before it's assigned throws UninitializedPropertyAccessException. lateinit works only with var, non-null types and not with primitive types like Int.

lazy

val x by lazy { … } computes the value the first time it's read and caches it. Ideal for expensive setup that might not be needed:

kotlin · try it yourself
class Report(val rows: List<Int>) {
    val summary: String by lazy {
        println("(computing summary...)")
        "rows=${rows.size}, total=${rows.sum()}"
    }
}

fun main() {
    val r = Report(listOf(4, 8, 15, 16, 23, 42))
    println("Report created")
    println(r.summary)
    println(r.summary)
}
Report created
(computing summary...)
rows=6, total=108
rows=6, total=108

Summary

Need Use
value derived from other properties custom get()
validate or react to assignments custom set(value) with field
public read, private write var x = 0 + private set
non-null value assigned after construction lateinit var
expensive value computed on first use val x by lazy { … }
compile-time constant const val (top level or in an object)

Tip: lazy and observable are examples of delegated properties (by). The standard library also offers Delegates.observable { prop, old, new -> … } to react to changes and by map to read properties from a map.

Test yourself

Inside a custom setter, how do you store the new value?

  1. this.prop = value
  2. field = value
  3. set(value)
  4. prop = value

When is the block of val x by lazy { ... } executed?

  1. At construction
  2. Every time x is read
  3. The first time x is read, then cached
  4. Never

Which declaration is valid?

  1. lateinit val name: String
  2. lateinit var count: Int
  3. lateinit var name: String
  4. lateinit var name: String?