0
0
Kotlinprogramming~3 mins

Why Function references (::functionName) in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could pass a function like a simple value and make your code way cleaner?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
val doubled = numbers.map { x -> double(x) }
After
val doubled = numbers.map(::double)
What It Enables

It lets you write clearer and more reusable code by treating functions as simple values you can pass around.

Real Life Example

When sorting a list of names by length, you can pass the length function directly instead of writing a custom comparator every time.

Key Takeaways

Manual loops are slow and error-prone.

Function references simplify passing functions as values.

Code becomes cleaner, shorter, and easier to maintain.