liveBook · Manning

Member reference

As explained in Kotlin in Action, 2E

A member reference is a Kotlin expression that refers to a class or object member as a callable value.

A member reference is a Kotlin expression that converts a method or property into a callable value. The :: operator lets functions such as collection operators receive existing behavior directly instead of wrapping it in a redundant lambda. section 5.1.5 section 1.2.3

Replace a selector lambda

data class Person(val name: String, val age: Int) val people = listOf(Person("Alice", 29), Person("Bob", 31)) println(people.maxByOrNull(Person::age)) // Person(name=Bob, age=31) Person::age has the same function type as { person: Person -> person.age }. It refers to the property; it does not invoke it, so parentheses are omitted. section 5.1.2 section 5.1.5

Use the same syntax for several callable forms:

  • Reference a method with ClassName::method, such as ::sendEmail when the function is top-level. section 5.1.5
  • Reference a property with ClassName::property, such as Person::age. section 5.1.5
  • Reference a constructor with ::ClassName, store the action, and create an instance later. section 5.1.5
  • Reference an extension function through its receiver type, such as Person::isAdult. section 5.1.5
data class Person(val name: String, val age: Int)
 
fun main() {
    val createPerson = ::Person         #1
    val p = createPerson("Alice", 29)
    println(p)
    // Person(name=Alice, age=29)
}

A constructor reference can be stored as a value and invoked later with constructor arguments. section 5.1.5

How Kotlin in Action, 2E covers it

How deep it goes
Explains syntax, callable equivalence, top-level functions, constructors, and extension functions without detailing compiler or runtime internals.
Examples
Demonstrates Person::age, ::salute, ::sendEmail, ::Person, and Person::isAdult in collection, invocation, construction, and predicate examples.
What it assumes
Assumes familiarity with lambdas and function arguments while teaching the distinction between invoking a callable and passing its reference.
What you can do after
Apply it via Kotlin's :: syntax to pass methods, properties, constructors, and extension functions wherever compatible lambdas are accepted.
How it connects
Connects member references with lambdas, function types, higher-order functions, collection operations, constructors, and extension functions.

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.