Properties and explicit backing fields
suggest changeA Kotlin property isn't a field. It's a getter (and for var, a setter) that may or may not store its value in a hidden backing field. Callers always go through the accessors, so you can start with a plain val name: String and later add validation, computation or lazy loading without changing any code that uses it.
This article covers:
- default and custom getters and setters
- the
fieldidentifier and when a backing field exists private setlateinitand::x.isInitialized- explicit backing fields (
val items: List<T> field = mutableListOf()), new in Kotlin 2.3/2.4, which replace the old_items/itemspattern
Versions:
- Explicit backing fields were added in Kotlin 2.3 as an experimental feature, enabled with
-Xexplicit-backing-fields. - In Kotlin 2.4 they're stable and need no flag. Passing it only prints
warning: the argument '-Xexplicit-backing-fields' is redundant for the current language version 2.4. - Everything else here has been in Kotlin since 1.0 (
isInitializedsince 1.2).
All examples were compiled with Kotlin 2.4.21 on JDK 25.
Properties are accessors
A property declared in a class body or in the primary constructor gets a default getter, a default setter if it's a var, and a private field that holds the value:
class Person(val name: String) {
var age: Int = 0
}
On the JVM, name becomes a private field plus getName(), and age becomes a field plus getAge() and setAge(int). Kotlin code writes p.age = 30, which calls setAge(30). Java code calls the methods directly.
A property must be initialized: with an initializer, in an init block or constructor, or with lateinit. Otherwise:
e1.kt:6:5: error: property must be initialized or be abstract.
var x: Int
^^^^^^^^^^
See Constructors and init blocks for the order in which initializers run.
Custom getters
Write get() after the property to compute its value on every read. A property whose getter doesn't use a field has no storage at all:
class Rectangle(val width: Int, val height: Int) {
// computed on every access, no backing field
val area: Int
get() = width * height
// type inferred from the getter
val isSquare get() = width == height
}
fun main() {
val r = Rectangle(3, 4)
println("area=${r.area} square=${r.isSquare}")
println(Rectangle(5, 5).isSquare)
}
Output:
area=12 square=false
true
javap shows that area and isSquare have methods but no fields. Note that a Boolean property named isX keeps its name for the Java getter:
public final class Rectangle {
private final int width;
private final int height;
public Rectangle(int, int);
public final int getWidth();
public final int getHeight();
public final int getArea();
public final boolean isSquare();
}
Because the property has no field, it can't have an initializer:
class R(val w: Int, val h: Int) {
val area: Int = 0
get() = w * h
}
e1.kt:2:21: error: initializer is prohibited here because this property has no backing field.
val area: Int = 0
^
Initializer or getter?
val x = expr evaluates expr once, when the object is created. val x get() = expr evaluates it on every read. They look similar but behave very differently when expr has side effects or depends on changing state:
class Session {
private var counter = 0
val idOnce = ++counter // initializer: runs once, value stored in a field
val idEachTime get() = ++counter // getter: runs on every read
var nickname: String = ""
get() = field.ifEmpty { "anonymous" }
}
fun main() {
val s = Session()
println("${s.idOnce} ${s.idOnce} ${s.idOnce}")
println("${s.idEachTime} ${s.idEachTime} ${s.idEachTime}")
println(s.nickname)
s.nickname = "kjk"
println(s.nickname)
}
Output:
1 1 1
2 3 4
anonymous
kjk
nickname shows a getter that still has a backing field: it reads it with field and transforms the stored value.
Guidelines from the Kotlin coding conventions: a getter should be cheap, shouldn't throw for a valid object and should return the same value when the state hasn't changed. A getter like idEachTime that changes state on every read is a bug magnet; make it a function. For a value that's expensive to compute but doesn't change, use by lazy (see Lazy initialization).
Custom setters and field
A setter receives the new value (named value by convention) and decides what to store. Inside the accessors, field refers to the backing field:
class Temperature {
var celsius: Double = 0.0
set(value) {
require(value >= -273.15) { "below absolute zero: $value" }
field = value
}
var fahrenheit: Double
get() = celsius * 9 / 5 + 32
set(value) {
celsius = (value - 32) * 5 / 9
}
}
fun main() {
val t = Temperature()
t.celsius = 100.0
println("${t.celsius} C = ${t.fahrenheit} F")
t.fahrenheit = 32.0
println("${t.celsius} C = ${t.fahrenheit} F")
try {
t.celsius = -300.0
} catch (e: IllegalArgumentException) {
println("error: ${e.message}")
}
}
Output:
100.0 C = 212.0 F
0.0 C = 32.0 F
error: below absolute zero: -300.0
Kotlin generates a backing field only if at least one accessor is the default one or uses field. celsius has a default getter and a setter that uses field, so it gets a field. Both accessors of fahrenheit are custom and neither uses field, so it's stored in celsius:
public final class Temperature {
private double celsius;
public Temperature();
public final double getCelsius();
public final void setCelsius(double);
public final double getFahrenheit();
public final void setFahrenheit(double);
}
Note that the initializer = 0.0 is assigned to the field directly and doesn't go through the setter, so the validation doesn't run for it.
private set and the recursion trap
To make a property read-only from outside but writable inside the class, change the setter's visibility without giving it a body:
class Counter {
var count = 0
private set
var name: String = ""
set(value) {
field = value.trim()
}
fun increment() {
count++
}
}
class Broken {
var size: Int = 0
set(value) {
size = value // calls the setter again
}
}
fun main() {
val c = Counter()
c.increment()
c.increment()
c.name = " clicks "
println("${c.name}: ${c.count}")
// c.count = 10 // error: cannot access 'count': it is private in 'Counter'
try {
Broken().size = 1
} catch (e: StackOverflowError) {
println("StackOverflowError")
}
}
Output:
clicks: 2
StackOverflowError
Inside an accessor, the property name means "call the accessor", so size = value in its own setter recurses forever. The compiler doesn't warn about it. Always write field = value.
Accessors can also be open and overridden; see Overriding properties and methods. Interfaces can declare properties, but their accessors can't use field because an interface has no state; see Interface with default implementations. To reuse accessor logic across properties (observing changes, vetoing values, storing in a map), use Delegated properties.
lateinit
Sometimes a non-null value can't be provided in the constructor: it's injected by a framework, set in a test's @BeforeEach, or created in Android's onCreate. Making it nullable forces !! or ?. on every use. lateinit var keeps the type non-null and checks on read instead:
class Database(val url: String) {
fun query(sql: String) = "result of '$sql' from $url"
}
class ReportService {
lateinit var db: Database
fun isReady() = this::db.isInitialized
fun run(): String = db.query("select 1")
}
fun main() {
val service = ReportService()
println("ready: ${service.isReady()}")
try {
service.run()
} catch (e: UninitializedPropertyAccessException) {
println("${e::class.simpleName}: ${e.message}")
}
service.db = Database("jdbc:sqlite:app.db") // e.g. set by a DI framework or a test setup
println("ready: ${service.isReady()}")
println(service.run())
}
Output:
ready: false
UninitializedPropertyAccessException: lateinit property db has not been initialized
ready: true
result of 'select 1' from jdbc:sqlite:app.db
Reading the property before assignment throws UninitializedPropertyAccessException with the property name, which is far easier to debug than a NullPointerException somewhere later.
::db.isInitialized tells you whether it was assigned. It's only available where the backing field is accessible: in the class that declares the property (including lambdas and nested classes inside it), or in the same file for a top-level property. From anywhere else you get:
e2.kt:9:27: error: backing field of 'var ok: String' is not accessible at this point.
fun check(b: Bad) = b::ok.isInitialized
^^^^^^^^^^^^^
If callers need to know, expose a function like isReady() above.
lateinit has restrictions, all reported by the compiler:
class Bad {
lateinit var count: Int
lateinit var name: String?
lateinit val id: String
lateinit var title: String
get() = field.uppercase()
}
e2.kt:2:5: error: 'lateinit' modifier is not allowed on properties of primitive types.
e2.kt:3:5: error: 'lateinit' modifier is not allowed on properties of a type with nullable upper bound.
e2.kt:4:5: error: 'lateinit' modifier is allowed only on mutable properties.
e2.kt:5:5: error: 'lateinit' modifier is not allowed on properties with a custom getter or setter.
The reason is that "not initialized" is represented as null in the field, so the type must be a non-null reference type. For Int, Long and friends use Delegates.notNull() (see Delegated properties). For a value that can be computed on first use, prefer val ... by lazy { }, which is also read-only and thread-safe.
lateinit works on class properties, top-level properties and local variables. On the JVM the backing field of a lateinit property is exposed with the visibility of the setter, which is what injection frameworks need:
public final class ReportService {
public Database db;
...
Exposing mutable state: the backing property pattern
A common need: a class changes a collection internally, but callers should only read it. Before Kotlin 2.4 you wrote two properties, a private mutable one with an underscore and a public read-only one that returns it:
class TodoListOld {
private val _items = mutableListOf<String>()
val items: List<String> get() = _items
fun add(item: String) {
_items.add(item)
}
}
The same pattern is everywhere in coroutines and Android code:
private val _state = MutableStateFlow(UiState())
val state: StateFlow<UiState> = _state.asStateFlow()
It works, but it's two names for one thing, and inside the class you must remember to use _items for writes and either name for reads. The Flows and Immutability articles use it.
Explicit backing fields
Kotlin 2.4 lets you declare the backing field yourself, with a more specific type than the property:
class TodoList {
val items: List<String>
field = mutableListOf()
fun add(item: String) {
items.add(item) // inside the class, items is a MutableList<String>
}
fun removeDone(done: Set<String>) {
items.removeAll(done)
}
}
fun main() {
val todo = TodoList()
todo.add("write tests")
todo.add("fix bug")
todo.add("release")
todo.removeDone(setOf("fix bug"))
println(todo.items)
println(todo.items.size)
// todo.items.add("x") // error: unresolved reference 'add' on receiver of type 'List<String>'
}
Output:
[write tests, release]
2
How to read it:
val items: List<String>is the public type that callers see.field = mutableListOf()declares the backing field and its initializer. Its type is inferred from the initializer (hereMutableList<String>, using the property type to inferString); you can also write it explicitly:field: MutableList<String> = mutableListOf().- Inside the class,
itemsis automatically smart cast to the field type, soitems.add(...)compiles. Outside, it's aList<String>.
The compiled class has one field and one getter, the same as the hand-written version minus the extra property:
public final class TodoList {
private final java.util.List<java.lang.String> items;
public TodoList();
public final java.util.List<java.lang.String> getItems();
public final void add(java.lang.String);
public final void removeDone(java.util.Set<java.lang.String>);
}
StateFlow and SharedFlow
The biggest win is in state holders, where the old pattern needed _state / state and _events / events pairs:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
data class UiState(val loading: Boolean = false, val user: String? = null)
class ProfileViewModel(private val scope: CoroutineScope) {
val state: StateFlow<UiState>
field = MutableStateFlow(UiState())
val events: SharedFlow<String>
field = MutableSharedFlow(extraBufferCapacity = 8)
fun load(id: Int) = scope.launch {
state.update { it.copy(loading = true) }
delay(50) // pretend to fetch the user
state.value = UiState(loading = false, user = "user-$id")
events.emit("loaded $id")
}
}
fun main() = runBlocking {
val vm = ProfileViewModel(this)
val watcher = launch {
vm.state.collect { println("state: $it") }
}
val eventWatcher = launch {
vm.events.collect { println("event: $it") }
}
yield()
vm.load(42).join()
delay(10)
println("current: ${vm.state.value.user}")
watcher.cancel()
eventWatcher.cancel()
}
Output (with kotlinx-coroutines-core 1.11.0):
state: UiState(loading=false, user=null)
state: UiState(loading=true, user=null)
state: UiState(loading=false, user=user-42)
event: loaded 42
current: user-42
Inside the class, state.update { }, state.value = ... and events.emit(...) work because state is a MutableStateFlow and events a MutableSharedFlow there. Outside, vm.state.value = ... doesn't compile (error: 'val' cannot be reassigned.) because StateFlow.value is read-only.
Initializing in init and other field types
The field can be any subtype of the property type, and it can be initialized in an init block instead of inline:
class Inventory {
val stock: Map<String, Int>
field = HashMap()
val history: List<String>
field: ArrayList<String>
init {
history = ArrayList(16)
history.add("created")
}
fun receive(item: String, n: Int) {
stock.merge(item, n, Int::plus)
history.add("+$n $item")
}
}
fun main() {
val inv = Inventory()
inv.receive("apple", 5)
inv.receive("apple", 3)
println(inv.stock)
println(inv.history)
// the getter returns the field itself, so a cast still gets through
(inv.history as MutableList<String>).clear()
println(inv.history)
}
Output:
{apple=8}
[created, +5 apple, +3 apple]
[]
The last lines show what explicit backing fields are not: protection. The getter returns the field object itself, exactly like get() = _items did. A caller that casts can modify it. That's usually acceptable (casting a List to MutableList is clearly misuse), but if the data must not leak, return a copy (get() = _items.toList()) or an immutable collection, and keep the old pattern, since explicit backing fields can't have a custom getter. Similarly, _state.asStateFlow() wraps the flow in a read-only object, while an explicit field returns the MutableStateFlow instance.
Where the smart cast applies
The property has the field's type wherever the field is visible, which is the private scope of the class: its members, lambdas, nested and inner classes, and the companion object. It also works on other instances of the same class (other.items.add(...)). It doesn't apply in extension functions, even in the same file:
fun TodoList.addEach(xs: List<String>) {
items.addAll(xs)
}
t4.kt:19:11: error: unresolved reference 'addAll' on receiver of type 'List<String>'.
items.addAll(xs)
^^^^^^
For a top-level property, the scope is the file.
Rules
The compiler enforces these restrictions in Kotlin 2.4.21:
| Declaration | Error |
|---|---|
var x: List<T> with a field |
only 'val' properties with explicit backing fields are supported. |
a get() next to field = ... |
properties with explicit backing fields cannot have accessors. |
open val |
properties with explicit backing fields must be final. |
private val |
private properties cannot have explicit backing fields. |
val s: String with field: Any = ... |
the type of the backing field must be a subtype of the property's type. |
in an interface |
backing fields inside interfaces are prohibited. |
val x by lazy { } with a field |
delegated properties cannot have explicit backing field declarations. |
lateinit field |
modifier 'lateinit' is not applicable to 'backing field'. |
Public, internal and protected properties are allowed, in classes, objects and at the top level.
If a project still compiles with -language-version 2.3 (or languageVersion in Gradle's compilerOptions), you get:
t3.kt:3:9: error: the feature "explicit backing fields" is only available since language version 2.4
field = mutableListOf()
^^^^^^^^^^^^^^^^^^^^^^^
With language version 2.3, adding -Xexplicit-backing-fields enables it as the experimental feature it was in 2.3. Libraries that must support older Kotlin versions should stay with _items / items.
Summary
| You want | Write |
|---|---|
| a stored property | val x = 1 / var x = 1 |
| a computed property | val x get() = a + b |
| validate or transform on write | var x = 0; set(value) { require(...); field = value } |
| read-only outside, writable inside | var x = 0; private set |
| non-null value assigned after construction | lateinit var x: Service |
| check whether it was assigned | this::x.isInitialized |
| computed once on first use | val x by lazy { ... } |
| mutable inside, read-only type outside | val x: List<T> field = mutableListOf() (Kotlin 2.4) |
| a defensive copy for callers | private val _x = mutableListOf<T>(); val x get() = _x.toList() |
For more property techniques see Delegated properties, Observable properties, Constants and Visibility Modifiers.