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
