liveBook · Manning

setValue

As explained in Kotlin in Action, 2E

setValue is a Kotlin property-delegation operator function that stores a delegated property's value using a receiver and property reference.

setValue is the operator function that receives writes to a delegated var. Its receiver identifies the object, its KProperty reference identifies the property, and newValue carries the assigned value. section 9.5.3 section 9.5.1

An observable delegate

class ObservableProperty(var propValue: Int, val observable: Observable) { operator fun getValue(thisRef: Any?, prop: KProperty<*>): Int = propValue operator fun setValue(thisRef: Any?, prop: KProperty<*>, newValue: Int) { val oldValue = propValue propValue = newValue observable.notifyObservers(prop.name, oldValue, newValue) } } class Person(val name: String, age: Int, salary: Int) : Observable() { var age by ObservableProperty(age, this) var salary by ObservableProperty(salary, this) }

When age changes, Kotlin forwards the assignment to the delegate’s setValue. The function can retain the old value, store the new one, and use prop.name to report which property changed. section 9.5.3

The same convention supports other storage strategies:

  • A MutableMap supplies setValue automatically, using the delegated property’s name as its key. section 9.5.5
  • A database framework can implement setValue on Column to update the corresponding database field when a property changes. section 9.5.6
operator fun <T> Column<T>.getValue(o: Entity, desc: KProperty<*>): T
{
   // retrieve the value from the database
}
operator fun <T> Column<T>.setValue(o: Entity, desc: KProperty<*>, value: T)
{
   // update the value in the database
}

Inspect the generic Column setValue signature used to connect delegated assignments with database updates. section 9.5.6

How Kotlin in Action, 2E covers it

How deep it goes
Defines the operator signature and execution flow, but defers broader property-reference details.
Examples
Uses observable Person properties, map-backed attributes, and database-backed User properties as concrete implementations.
What it assumes
Assumes basic Kotlin properties and lambdas while introducing delegation conventions and KProperty parameters.
What you can do after
Build custom delegated var behavior that stores values and reacts to assignments.
How it connects
Connects delegated properties with operator overloading, KProperty, MutableMap, observable properties, and database columns.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.