0
0
Kotlinprogramming~5 mins

Function references (::functionName) in Kotlin

Choose your learning style9 modes available
Introduction

Function references let you use a function as a value. This helps when you want to pass a function to another function or store it for later.

When you want to pass a function as an argument to another function.
When you want to store a function in a variable to call it later.
When you want to simplify lambda expressions by referring directly to a function.
When you want to use existing functions with collection operations like map or filter.
When you want to improve code readability by avoiding anonymous functions.
Syntax
Kotlin
val reference = ::functionName

The double colon (::) is used before the function name to get its reference.

You can use this reference to call the function or pass it around.

Examples
Store a reference to a function with no parameters and call it later.
Kotlin
fun greet() {
    println("Hello!")
}

val greetRef = ::greet

greetRef()
Reference a function with parameters and use it like a variable holding a function.
Kotlin
fun square(x: Int) = x * x

val squareRef: (Int) -> Int = ::square

println(squareRef(5))
Use a function reference with collection operations like map.
Kotlin
fun square(x: Int) = x * x
val numbers = listOf(1, 2, 3)
val doubled = numbers.map(::square)
println(doubled)
Sample Program

This program stores a reference to the greet function and calls it through the reference.

Kotlin
fun greet() {
    println("Hello, Kotlin!")
}

fun main() {
    val greetFunction = ::greet
    greetFunction()
}
OutputSuccess
Important Notes

Function references can refer to top-level functions, member functions, or constructors.

When using member function references, you may need an instance to call the function.

Function references improve code clarity by avoiding verbose lambda expressions.

Summary

Function references use :: before a function name to treat it as a value.

They let you pass or store functions easily.

They work well with collections and higher-order functions.