1. When a lambda turns into a “wrapper just to be a wrapper”
When you’ve just learned lambdas, there’s a dangerous period: you want to wrap absolutely everything in a lambda. It’s like buying an electric screwdriver and using it to twist off a bottle cap. Formally it works, but even your cat and the compiler start giving you weird looks. Most often the problem shows up when the lambda does exactly one thing: it simply calls another function.
Let’s look at a typical situation. We have a predicate function isShort, and we want to pass it to a higher-order function that expects (String) -> Boolean.
fun isShort(s: String): Boolean = s.length <= 3
fun findFirstOrNull(items: List<String>, predicate: (String) -> Boolean): String? {
for (s in items) if (predicate(s)) return s
return null
}
fun main() {
val words = listOf("kotlin", "go", "java")
val result = findFirstOrNull(words) { s -> isShort(s) } // wrapper lambda
println(result) // go
}
Here the lambda { s -> isShort(s) } doesn’t add anything: it just “forwards” the argument into isShort. In such cases, Kotlin lets you write it shorter and, usually, more readable.
2. What a callable reference :: is and how to read it
Callable reference is a way to turn an existing function (or something else “callable”, for example a constructor) into a value that you can pass as a parameter. Essentially, it’s a “function reference” as a value compatible with a function type. Kotlin treats callable references as one way to “get an instance of a function type” alongside lambdas.
Syntax looks like this:
- ::isShort — a reference to the function isShort
- String::toInt — a reference to a function/method you can call on String (for now, think of it as a “ready-made string-to-number conversion”)
- ::Regex — a reference to a constructor (we’ll mention it in passing, without going deep)
Today we’re mainly interested in the first form: ::functionName.
How to read ::
A convenient mental translation:
- { x -> f(x) } reads as “a lambda that calls f”
- ::f reads as “the function f itself, as a value”
That is, we are not calling f, we are passing it.
As a sketch (a simple “mental map”):
flowchart LR
A["Wrapper lambda
{ x -> f(x) }"] --> B["Callable reference
::f"]
B --> C["Higher-order function
expects (T)->R"]
3. Replacing { x -> f(x) } with ::f
In this section, we’ll carefully move from “yeah, it’s shorter” to understanding when it’s truly the same thing and when it’s not. It’s important not to fall into the trap: :: is not a “magical shortening trick”, but a strict feature that the compiler type-checks.
Let’s return to the example and rewrite it using a callable reference:
fun isShort(s: String): Boolean = s.length <= 3
fun findFirstOrNull(items: List<String>, predicate: (String) -> Boolean): String? {
for (s in items) if (predicate(s)) return s
return null
}
fun main() {
val words = listOf("kotlin", "go", "java")
val result = findFirstOrNull(words, ::isShort)
println(result) // go
}
The key point: ::isShort fits because the signatures match:
- expected: (String) -> Boolean
- isShort has: (String) -> Boolean
That’s exactly why the compiler can calmly “substitute” the function where a lambda is needed.
4. Signature matching: why :: sometimes doesn’t compile
With callable references there’s one good piece of news and one… also good piece of news, it just annoys you at first.
Good news: if ::f compiles, then type-wise everything matched.
Second good news: if it doesn’t compile, the compiler saved you because you were trying to pass “the wrong behavior”. And it’s better to find out now than after two hours of debugging and philosophical questions about life.
The number of parameters didn’t match
Imagine we want to pass a function that takes two arguments into a place that expects one.
fun startsWithPrefix(s: String, prefix: String): Boolean = s.startsWith(prefix)
fun usePredicate(items: List<String>, predicate: (String) -> Boolean): Int {
var count = 0
for (x in items) if (predicate(x)) count++
return count
}
fun main() {
val words = listOf("kotlin", "koala", "java")
usePredicate(words, ::startsWithPrefix) // Will NOT compile: 1 parameter expected, but the function has 2
}
Here ::startsWithPrefix has type (String, String) -> Boolean, but the expected type is (String) -> Boolean. The compiler honestly says: “doesn’t match”.
What to do? In this case, a callable reference does not replace the lambda, because the lambda really adds logic here: “capture prefix”.
fun main() {
val words = listOf("kotlin", "koala", "java")
val prefix = "ko"
val count = usePredicate(words) { s -> startsWithPrefix(s, prefix) }
println(count) // 2
}
And that’s totally fine: the lambda does useful work (mixes in an external parameter).
The return type didn’t match
If (String) -> Boolean is expected and you try to pass a function (String) -> Int, Kotlin won’t let you create chaos either.
fun lengthOf(s: String): Int = s.length
fun usePredicate(items: List<String>, predicate: (String) -> Boolean): Int {
var count = 0
for (x in items) if (predicate(x)) count++
return count
}
fun main() {
val words = listOf("a", "bbb", "cc")
usePredicate(words, ::lengthOf) // Will NOT compile: Int does not turn into Boolean
}
This is not “the language nitpicking”, it’s basic safety: a predicate must return true/false, not “2, because the length is 2” (even though it sounds like dream-logic from a programmer).
5. Callable reference as a value: you can store it in a val and call it
To feel that ::f is truly a value, it’s useful to do it “head-on” once: store a reference to a function in a variable, and then call it.
It’s also a great way to stop confusing “pass” with “call”.
fun normalize(s: String): String = s.trim().lowercase()
fun main() {
val f: (String) -> String = ::normalize
println(f(" HeLLo ")) // hello
}
We are not calling normalize directly; we are calling f(...), and inside f there is a reference to normalize.
By the way, Kotlin’s documentation on lambdas and function types lists callable references as a separate way to create a function-type value. That’s exactly what this is: “a function as a value”.
6. Where :: improves readability, and where it gets in the way
With callable references it’s easy to fall into two extremes.
The first extreme is writing wrapper lambdas everywhere, even if it’s just a one-liner f(x).
The second extreme is replacing with :: absolutely everywhere, even when there’s additional logic. Then the code becomes “too clever”: compact, but unclear.
To decide, it helps to keep a simple table in mind:
| Situation | Better | Why |
|---|---|---|
| The lambda calls exactly one function with no changes | ::f | Remove noise like { x -> f(x) } |
| You need to capture an external parameter or add a check | lambda { x -> ... } | That’s not “just a call” anymore; it’s logic |
| The function name explains the step well | ::f | The code becomes self-documenting |
| The function name is bad/abstract (doIt, process) | often a lambda, or rename | Otherwise ::doIt explains nothing |
And yes: if you see ::doIt in code, it’s almost always a signal “rename the function”, not “understand the philosophy of doIt”.
7. Mini example: building a “pseudo-map” with ::
We’re not using the standard collection operations map/filter/find as the main tool yet (that comes later per the plan). So let’s make a training analog: a function that applies a transformation to each element of a list using a plain for.
First, let’s write a higher-order function:
fun transformAll(items: List<String>, transform: (String) -> String): List<String> {
val result = mutableListOf<String>()
for (x in items) result.add(transform(x))
return result
}
Now imagine we want to normalize user input: trim spaces and convert to lowercase.
Option 1: wrapper lambda (works, but is noisy)
fun normalize(s: String): String = s.trim().lowercase()
fun main() {
val raw = listOf(" ADD ", " LiSt", " remove ")
val normalized = transformAll(raw) { x -> normalize(x) }
println(normalized) // [add, list, remove]
}
Option 2: callable reference (shorter and more honest)
fun normalize(s: String): String = s.trim().lowercase()
fun main() {
val raw = listOf(" ADD ", " LiSt", " remove ")
val normalized = transformAll(raw, ::normalize)
println(normalized) // [add, list, remove]
}
Here ::normalize is perfect: it describes the step exactly and contains no “hidden magic”.
8. Embedding :: into a CLI expense app
Now we’ll make a small but realistic improvement to the console app you built the other day about collections and the add/list/remove commands. We don’t have classes and objects yet, so we’ll store expenses as a list of pairs: Pair<String, Int>, where first is the title and second is the amount.
The idea of today’s improvement is simple: we want the code for the “processing steps” to be readable. Callable references are a great way to make steps “named”.
Base functions of the app
First, let’s sketch the minimal foundation (very briefly). There’s nothing new here; it’s just context:
fun addExpense(expenses: MutableList<Pair<String, Int>>, title: String, amount: Int) {
expenses.add(title to amount)
}
fun printExpenses(expenses: List<Pair<String, Int>>) {
if (expenses.isEmpty()) {
println("No expenses yet") // No expenses yet
return
}
for ((title, amount) in expenses) println("$title: $amount")
}
The “normalize command” step as a separate function
Previously, many people write normalization directly in main, roughly like this: val cmd = readln().trim().lowercase(). That’s fine, but when the logic grows, you want to extract the step into a function.
fun normalizeCommandLine(line: String): String = line.trim().lowercase()
And here callable references start to shine: we can pass this step as a parameter without smearing logic across main.
A higher-order function: “read a line and prepare it”
Let’s make a simple utility: it reads a line, applies a transformation, and returns the result. This resembles the “read → prepare → parse” pattern you already used in the input topics.
fun readPreparedLine(prepare: (String) -> String): String {
val raw = readln()
return prepare(raw)
}
Now in main we can do this:
fun main() {
println("Enter a command:")
val line = readPreparedLine(::normalizeCommandLine)
println("Command: $line")
// If you enter " LiSt ", you'll get: Command: list
}
Here ::normalizeCommandLine is a perfect fit: the function already exists, its name is clear, and the signature (String) -> String matches what’s required.
9. :: in predicates: code becomes “conversational”
Callable references work especially nicely with predicates, because a predicate can often be expressed as one clear function with a good name.
Imagine we store expense titles and want to find the first expense with a short title (for example, “tea”) or, conversely, something “long and suspicious” (for example, “some unclear subscription to something”).
Let’s make a predicate as a named function:
fun isShortTitle(title: String): Boolean = title.length <= 3
And we’ll use our search function from the previous lecture (I’ll show it again in full so we don’t jump across files):
fun findFirstOrNull(items: List<String>, predicate: (String) -> Boolean): String? {
for (s in items) {
if (predicate(s)) return s
}
return null
}
Now a readable call:
fun main() {
val titles = listOf("coffee", "tea", "subscription")
val firstShort = findFirstOrNull(titles, ::isShortTitle)
println(firstShort) // tea
}
If you read this out loud, it becomes almost a normal sentence: “find the first or null by the rule isShortTitle”. And that’s exactly why we’re learning :: today: less noise, more meaning.
Function name as part of documentation
A callable reference amplifies the impact of naming: the function name becomes a “label for behavior”. That’s why functions that sound like an action or a rule look especially good with ::: normalizeCommandLine, isShortTitle, parseAmountOrNull.
If the function name is poor, :: will only highlight the problem. For example:
fun doIt(s: String): String = s.trim()
// transformAll(items, ::doIt) // technically ok, but readability... well, you get it
If you notice code with :: looks weird, it’s often a sign that you shouldn’t “switch back to a lambda”, but simply rename the function.
10. Common mistakes when using callable references ::
Mistake #1: confusing “passing a function” with “calling a function”.
One of the most common mix-ups looks like this: a student writes findFirstOrNull(words, isShort(words[0])) and wonders why everything broke. Because isShort(words[0]) is already a Boolean, but you need to pass (String) -> Boolean. In such places, it helps to say it out loud: ::isShort — I’m passing it; isShort("go") — I’m calling it.
Mistake #2: trying to use :: where the lambda really does extra work.
When you need to “mix in” an external parameter, a callable reference usually doesn’t fit — and that’s normal. The lambda { s -> startsWithPrefix(s, prefix) } is not a wrapper; it captures prefix. At that point, :: isn’t “worse”; it’s simply for a different situation.
Mistake #3: being surprised the compiler rejects ::f, even though it “seems to fit by meaning”.
Callable references live in a world of strict types: if (T) -> R is expected, the passed function must have exactly that signature. If there are more parameters or the return type is different, Kotlin won’t “guess”. This isn’t language pedantry; it’s protection from bugs that would otherwise surface too late.
Mistake #4: using :: with poorly named functions and getting unreadable code.
:: almost always improves code only when the function name speaks for itself. If the name is like process, handle, doStuff, then ::process doesn’t explain what’s happening. The result is shorter code, but not clearer code. The correct cure here is naming, not yet another lambda.
Mistake #5: trying to “cram :: everywhere” as a programming style.
A callable reference is a tool for targeted simplification. If you start replacing any lambdas with :: and in the process lose the ability to quickly understand the logic, you’ve shifted from engineering to the sport of “who can write it shorter”. In real projects, nobody gives awards for that sport — but people do often assign you to maintain the result.
GO TO FULL VERSION