Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 134 ยท Classes and Objects

Advanced Properties

Go deep on Kotlin properties: custom getters and setters, the field keyword, backing properties, lateinit, const val, extension properties and property references with examples.

In Java you write a private field plus a getter and a setter. In Kotlin you write a property, and the language supplies the accessors. Classes and Properties showed the basic form. Real programs soon need more: a value computed on demand, a setter that rejects bad input, a field that cannot be filled in the constructor, a constant known at compile time, or a way to talk about a property itself as a value.

This lesson goes through those tools one by one: custom accessors and the field identifier, backing properties, lateinit, const val, extension properties and property references. Each has a sharp edge that professionals learn to respect, and we will trigger the main ones on purpose so you recognize the error messages.

Custom getters and setters

A property declaration can be followed by a get() and (for var) a set(value) block. Inside the setter, the name field refers to the backing field, the hidden storage the compiler creates for you:

Kotlin A setter that clamps its input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two things are happening. level has a backing field because its accessors use field (or because it uses the default accessors). label has only a getter that does not mention field, so there is no storage at all: the expression runs on every read. Such a computed property cannot have an initializer, because there would be nowhere to put it.

Inside an accessor, never write level = ... or read level in the setter of level itself: that calls the accessor again and recurses until the stack overflows. Always use field inside the accessor of its own property.

Recursion through the property name is an easy mistake. Here it is on purpose:

Kotlin Using the property name inside its own setter (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program dies with Exception in thread "main" java.lang.StackOverflowError and a stack trace in which the line of the setter repeats. The fix is field = v + 1.

Getter that does work vs. stored value

A getter without field recomputes each time, which is perfect for cheap derived values (area, fullName, isEmpty) and wrong for expensive ones. For those, store the result with lazy (see Delegation) or in a regular property. A common style rule: a property getter should be cheap and free of side effects, otherwise make it a function (computeTotal()).

Different visibility for getter and setter

The getter always has the property's visibility. The setter can be narrower, which gives you a field that outsiders can read but only the class can change:

Kotlin Public getter, private setter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This pattern is everywhere in Kotlin: it keeps invariants inside the class. More about it in Encapsulation and Design.

Backing properties

Sometimes you want a mutable collection inside and a read-only view outside. The convention is a private property with an underscore and a public property with the clean name that exposes it through a read-only type:

Kotlin A backing property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Callers can read songs but the type List<String> has no add. Be aware that this is a read-only view, not a snapshot: it is the same list object, and a caller who casts it to MutableList could still modify it. If you need real protection, return _songs.toList(), which copies on every access.

lateinit: initialized later

A non-null property must have a value when the object is created. Sometimes that is impossible, for example when a framework or a test setup method fills in the field after construction. Marking a var with lateinit tells the compiler "I promise to set this before I read it":

Kotlin lateinit and isInitialized

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

If you break the promise, you get a run-time failure:

Kotlin Reading a lateinit before it is set (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property token has not been initialized. Rules to remember:

  • lateinit works only with var properties of non-null, non-primitive types (String, a class: yes; Int, String?: no).
  • It cannot have a custom getter or setter.
  • this::token.isInitialized checks the state; it is accessible only from inside the class (or its file for top-level properties).

Prefer constructor parameters whenever you can. lateinit hides a missing initialization until the first read, which is exactly the kind of error Kotlin tries to prevent. Good uses are dependency-injection fields and test fixtures. A nullable var token: String? = null is often the more honest choice.

const val: compile-time constants

A val is read-only, but its value may be computed at run time. A const val is a true constant that the compiler copies into every place it is used. It must be a primitive or String, initialized with a constant expression, and declared at the top level or inside an object or companion object:

Kotlin const val versus val

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Now the error that appears when the initializer is not a constant:

Kotlin const needs a compile-time value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports error: const 'val' initializer must be a constant value. A call to a function, even a trivial one, is not constant. Use a plain val in that case. Constants are written in SCREAMING_SNAKE_CASE by convention. const is also required to use a value in an annotation argument.

Extension properties

You can add a property to a type you do not own, just as with extension functions. Because an extension cannot add storage to the class, it must have a getter (and optionally a setter) and cannot have a backing field or an initializer:

Kotlin Extension properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Trying to store something fails:

Kotlin Extensions cannot have a backing field (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The message is error: extension property cannot be initialized because it has no backing field. Change = to get() = and it works. Extension properties are resolved statically by the declared type, so they never override anything.

Property references

A property is not a value in itself, but you can get a reference to it with ::. Person::name is a reference to the property on the class and takes an instance as input; person::name is bound to that instance. References are useful as arguments to functions like map, sortedBy and groupBy:

Kotlin Property references in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

KMutableProperty0 is the type of a bound reference to a var; the digit is the number of receivers still needed (0 for bound, 1 for Person::name). Reading .name, .get() and .set() works on our runner without any extra library, while deeper reflection such as listing all properties of a class needs the separate kotlin-reflect library (see Reflection Overview).

Putting it together: choosing the right kind

Situation Tool
Value derived from other state, cheap val with only a getter
Reject or normalize incoming values var with a setter using field
Outside may read, only the class may write private set
Mutable inside, read-only view outside backing property (_items)
Cannot be set in the constructor, will be set later lateinit var (or a nullable)
Known at compile time, primitive or String const val
Add a computed property to someone else's type extension property

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside set(value) { ... } of a property, which identifier gives access to the stored value?

    field is the backing field identifier, available only inside the accessors of that property. Using the property name instead calls the accessor again and recurses.
  2. 2. Which property is allowed to use lateinit?

    lateinit requires a var of a non-null, non-primitive type. Int is primitive-backed, val cannot be reassigned, and String? is nullable.
  3. 3. What happens when a lateinit property is read before it is assigned?

    The compiler cannot track the order of assignments, so the check happens at run time and throws kotlin.UninitializedPropertyAccessException.
  4. 4. Which declaration is a valid constant?

    const val needs a compile-time constant of a primitive or String type. Function calls and collections are not constant, and const var does not exist.
  5. 5. Why does val String.shout: String = "HEY" not compile?

    An extension cannot add storage to the receiver class, so it must compute its value in a getter: val String.shout: String get() = uppercase().

Summary

  • Properties can have custom get() and set(value) accessors; inside them use field, never the property name, to avoid infinite recursion.
  • A property without field in its accessors has no storage and is computed on each read.
  • private set gives read access to everyone and write access to the class only; backing properties (_x and x) expose a read-only view of a mutable value.
  • lateinit var postpones initialization for non-null, non-primitive types; reading it too early throws UninitializedPropertyAccessException. Check with ::x.isInitialized.
  • const val is a compile-time constant of a primitive or String, declared at top level or in an object.
  • Extension properties need a getter and cannot hold state.
  • Type::prop and instance::prop are property references; get, set and name work without kotlin-reflect.

Next: Equality and Identity