What if you could pass a function like a simple value and make your code way cleaner?
Why Function references (::functionName) in Kotlin? - Purpose & Use Cases
Imagine you have a list of numbers and you want to apply the same operation, like doubling each number. Doing this manually means writing a loop and calling the function for each item yourself.
Writing loops and calling functions manually is slow and repetitive. It's easy to make mistakes like calling the wrong function or forgetting to apply it to all items. This makes your code longer and harder to read.
Function references let you pass a function itself as a value, so you can reuse it easily without repeating code. This makes your code shorter, cleaner, and less error-prone.
val doubled = numbers.map { x -> double(x) }val doubled = numbers.map(::double)
It lets you write clearer and more reusable code by treating functions as simple values you can pass around.
When sorting a list of names by length, you can pass the length function directly instead of writing a custom comparator every time.
Manual loops are slow and error-prone.
Function references simplify passing functions as values.
Code becomes cleaner, shorter, and easier to maintain.