Kotlin Lambda Higher-Order Functions
In Kotlin, functions are first-class citizens: they can be assigned to variables, passed as arguments, and returned as values.
Treating functions as data gives rise to the concepts of function types, lambda expressions, and higher-order functions, which are also the reason Kotlin's collection operations are so concise.
This chapter starts with function types and gradually moves on to lambdas, closures, function references, and SAM conversion.
Function type
A function type describes "what parameters it takes and what value it returns", written as (parameter types) -> return type.
A function type is itself a type, so you can declare variables, pass it as an argument, and use it as a return value.
Example
// File path: LambdaType.kt
// Takes two Ints and returns an Int
val sum
:
(
Int, Int
)
->
Int
=
{
a, b
->
a
b
}
// Takes a String and returns a String
val greet
:
(
String
)
->
String
=
{
name
->
"Hello, $name"
}
// Takes no parameters and returns no meaningful value
val log
:
(
)
->
Unit
=
{
println
(
"RUNOOB"
)
}
// A value of the whole function type can be null; wrap it in an extra pair of parentheses
var callback
:
(
(
Int
)
->
Int
)
?
=
null
fun main
(
)
{
println
(
sum
(
1
,
2
)
)
println
(
greet
(
"Runoob"
)
)
log
(
)
callback
=
{
it
2
}
// callback may be null; use the safe call ?.invoke
println
(
callback
?
.
invoke
(
21
)
)
}
3
你好,Runoob
RUNOOB
42
You can also name parameters in a function type, e.g. (x: Int, y: Int) -> Int; these names are only hints and don't affect type matching.
There is also a function type with a receiver, written String.(Int) -> String, meaning the function is called on a String; this is exactly the function-type form of an extension function.
Example
// Function type with a receiver: receiver is String, parameter is Int, returns String
val repeatFun
:
String
.
(
Int
)
->
String
=
{
times
->
this
.
repeat
(
times
)
}
fun main
(
)
{
// Can be called like an extension function
println
(
"Run"
.
repeatFun
(
2
)
)
// Can also be used as an ordinary function type, in which case the receiver becomes the first parameter
val plain
:
(
String
, Int
)
->
String
=
repeatFun
println
(
plain
(
"RUNOOB"
,
2
)
)
}
RunRun
RUNOOBRUNOOB
Lambda Expression Syntax
A lambda is a block of code you can pass around, enclosed in curly braces, with parameters to the left of -> and the function body to the right.
The value of the last expression in the body is the lambda's return value.
Example
fun main
(
)
{
// Full syntax: when a parameter needs a type, write it after the parameter name
val sum
=
{
a
:
Int, b
:
Int
->
a
b
}
println
(
sum
(
3
,
4
)
)
// With a single parameter you can omit the declaration and use the implicit parameter it
val
double
:
(
Int
)
->
Int
=
{
it
2
}
println
(
double
(
5
)
)
// A lambda with no parameters
val hello
=
{
println
(
"Hello, Runoob"
)
}
hello
(
)
// Multi-line lambda: the last expression is the return value
val describe
=
{
value
:
Int
->
val text
=
if
(
value
0
)
"Positive number"
else
"Non-positive number"
"The result is $text"
}
println
(
describe
(
1
)
)
// Unused parameters can be placeholders with an underscore, supported since Kotlin 1.1
val second
=
{
_
:
Int, value
:
Int
->
value
}
println
(
second
(
1
,
2
)
)
}
7
10
Hello, Runoob
结果是 正数
2
Note:A lambda's type inference depends on context. When you write something like val f = { x -> x + 1 } with neither parameter types nor a clear target type in context, the compiler reports "cannot infer parameter type". The fix is to add type annotations or pass the lambda directly to a function with an explicit signature.
Higher-Order Functions
A function that takes a function as an argument or returns a function is called a higher-order function.
It abstracts "what to do" away from "how to do it", letting the caller decide the specific behavior.
Example
// Takes a function as an argument
fun calculate
(
a
:
Int, b
:
Int, operation
:
(
Int, Int
)
->
Int
)
:
Int
{
return
operation
(
a, b
)
}
// Returns a function: the return type is (Int) -> Int
fun multiplier
(
factor
:
Int
)
:
(
Int
)
->
Int
{
return
{
value
->
value
factor
}
}
fun main
(
)
{
// Trailing lambda syntax: the lambda is written outside the parentheses
println
(
calculate
(
6
,
3
)
{
a, b
->
a
b
}
)
println
(
calculate
(
6
,
3
)
{
a, b
->
a
b
}
)
// Get the function first, then call it
val triple
=
multiplier
(
3
)
println
(
triple
(
5
)
)
// Call the returned function directly
println
(
multiplier
(
10
)
(
4
)
)
}
9
18
15
40
When a function's last parameter is a function type, you can write the lambda outside the parentheses — this is trailing lambda syntax.
If it's the only parameter, the parentheses themselves can be omitted, giving rise to syntax like list.forEach { ... }.
Combining with Collections: forEach, filter, map
The collections library makes the fullest use of higher-order functions; the three most common are forEach, filter, and map.
The lambdas they receive decide what to do with each element, and they return a new collection rather than modifying the original.
Example
fun main
(
)
{
val sites
=
listOf
(
"runoob"
,
"RUNOOB"
,
"java"
,
"kotlin"
)
// forEach: executes a block of code for each element, returns Unit
sites.
forEach
{
println
(
it
)
}
println
(
"---"
)
// filter: keeps elements for which the lambda returns true, producing a new list
val upper
=
sites.
filter
{
it
==
it.
uppercase
(
)
}
println
(
upper
)
// map: transforms each element into another value, producing a new list
val lengths
=
sites.
map
{
it.
length
}
println
(
lengths
)
// Chained calls: filter first, then transform
val result
=
sites
.
filter
{
it.
startsWith
(
"r"
, ignoreCase
=
true
)
}
.
map
{
it.
uppercase
(
)
}
println
(
result
)
}
runoob
RUNOOB
java
kotlin
---
[RUNOOB]
[6, 6, 4, 6]
[RUNOOB, RUNOOB]
forEach is an inline function, and filter and map also take inline lambdas, so these operations don't create extra objects for the lambdas.
Use forEachIndexed when you need the index, and use destructuring on a Map when you need both key and value.
Example
fun main
(
)
{
val sites
=
listOf
(
"Runoob"
,
"www.runoob.com"
)
// forEachIndexed's lambda receives (index, value)
sites.
forEachIndexed
{
index, value
->
println
(
"$index -> $value"
)
}
// Map's forEach can destructure the key and value directly
val info
=
mapOf
(
"name"
to
"Runoob"
,
"site"
to
"www.runoob.com"
)
info.
forEach
{
(
key, value
)
->
println
(
"$key = $value"
)
}
}
0 -> Runoob
1 -> www.runoob.com
name = Runoob
site = www.runoob.com
Closures and Variable Capture
A lambda can access variables from the scope where it was defined; such a structure is called a closure.
Kotlin allows a captured variable to be var and also allows modifying it inside the lambda.
Example
fun main
(
)
{
var counter
=
0
// Capture the outer local variable counter and modify it
val increment
=
{
counter
++
}
increment
(
)
increment
(
)
println
(
"counter = $counter"
)
// Each call to makeCounter creates an independent closure
val c1
=
makeCounter
(
)
val c2
=
makeCounter
(
)
c1
(
)
c1
(
)
c2
(
)
println
(
"c1 = ${c1()}, c2 = ${c2()}"
)
}
// Return a function that holds its own count internally
fun makeCounter
(
)
:
(
)
->
Int
{
var count
=
0
return
{
count
++
count
// The value of the last expression is the return value
}
}
counter = 2
c1 = 3, c2 = 2
Each of the two closures holds its own count without affecting the other — this is the most typical use of closures: encapsulating state inside a function.
Anonymous functions
Lambdas aren't the only function literals; you can also use the fun keyword to define an anonymous function with no name.
A return inside an anonymous function returns only from the anonymous function itself and doesn't affect the outer function — unlike a lambda.
Example
fun main
(
)
{
// Anonymous function: has parameter and return types, starts with fun
val sum
=
fun
(
a
:
Int, b
:
Int
)
:
Int
{
return
a
b
// Returns from the anonymous function itself
}
println
(
sum
(
2
,
3
)
)
// Anonymous functions can also use an expression body
val square
=
fun
(
x
:
Int
)
=
x
x
println
(
square
(
6
)
)
// When passed to a higher-order function, a return inside the anonymous function won't return from main
listOf
(
1
,
2
,
3
,
4
)
.
forEach
(
fun
(
value
)
{
if
(
value
==
3
)
return
// Only ends this one call of the anonymous function
println
(
value
)
}
)
println
(
"End"
)
}
5
36
1
2
4
结束
Another feature of anonymous functions is that the return type can be written explicitly, making them more intuitive than lambdas when you need precise control over the return type.
Function References ::
If a function already has a name, you can use :: to turn it into a value of function type without wrapping it in another lambda.
Function references come in three kinds: top-level function references, bound references (already bound to an instance), and unbound references (which need a receiver passed in).
Example
// Top-level function
fun isEven
(
value
:
Int
)
=
value
%
2
==
0
class
Site
(
val name
:
String
)
{
fun hello
(
)
=
"Hello, $name"
}
fun main
(
)
{
val numbers
=
listOf
(
1
,
2
,
3
,
4
)
// ::isEven is equivalent to { value -> isEven(value) }
println
(
numbers.
filter
(
::
isEven
)
)
val site
=
Site
(
"Runoob"
)
// Bound reference: already bound to the site instance, so no receiver is needed when calling
val bound
=
site
::
hello
println
(
bound
(
)
)
// Unbound reference: the receiver must be passed as the first argument when calling
val unbound
:
(
Site
)
->
String
=
Site
::
hello
println
(
unbound
(
site
)
)
}
[2, 4]
你好,Runoob
你好,Runoob
When there are multiple overloaded functions with the same name, the compiler picks the matching reference based on the target function type.
Constructor References and Bound References
A constructor can also be referenced, written ::ClassName, producing a function that returns an instance of that class.
Which overloaded constructor is chosen is likewise determined by the target type.
Example
class
Site
(
val name
:
String
, val url
:
String
)
fun main
(
)
{
// The constructor reference ::Site is equivalent to a (String, String) -> Site function
val create
:
(
String
,
String
)
->
Site
=
::
Site
val runoob
=
create
(
"Runoob"
,
"www.runoob.com"
)
println
(
"${runoob.name} - ${runoob.url}"
)
// Use a constructor reference directly wherever a function is needed
val pairs
=
listOf
(
"Runoob"
to
"www.runoob.com"
,
"RUNOOB"
to
"kotlin.runoob.com"
)
val sites
=
pairs.
map
{
(
name, url
)
->
create
(
name, url
)
}
println
(
sites.
map
{
it.
name
}
)
}
Runoob - www.runoob.com
[Runoob, RUNOOB]
The create above is already a function-typed value and can be called inside map like an ordinary function.
Besides member functions, bound references can also refer to properties; for example site::name yields a getter function.
SAM Conversion
SAM is short for Single Abstract Method, referring to an interface with only one abstract method.
Kotlin allows a lambda to be converted directly into an instance of such an interface — this is SAM conversion.
Example
// Kotlin's functional interface: declared with fun interface, stable since Kotlin 1.4
fun
interface
StringChecker
{
fun check
(
value
:
String
)
:
Boolean
}
fun main
(
)
{
// A lambda is automatically converted into an instance of the functional interface
val notEmpty
=
StringChecker
{
it.
isNotEmpty
(
)
}
println
(
notEmpty.
check
(
"Runoob"
)
)
println
(
notEmpty.
check
(
""
)
)
// Interoperating with Java functional interfaces: Runnable has a single abstract method run()
val task
=
Runnable
{
println
(
"Running RUNOOB in a Java thread interface"
)
}
task.
run
(
)
}
true
false
在 Java 线程接口里运行 RUNOOB
Since Kotlin 1.4, Kotlin interfaces declared with fun interface also support SAM conversion; before that, SAM conversion only worked with Java interfaces.
An ordinary (non-functional) interface cannot be converted with a lambda even if it has only one method; you must write an object expression.
Common questions
Below are a few common questions about lambdas.
| Problem | Description |
|---|---|
| Where does a return inside a lambda return from | When passed to an inline function it returns from the outer function (non-local return); using return@label only ends the lambda |
| Do filter and map modify the original collection | No, they return new lists and the original collection stays unchanged |
| When can it be used | With one parameter the declaration can be omitted; with multiple parameters you must write the names yourself |
| How to choose between function references and lambdas | Prefer :: when a named function already exists; use a lambda when extra logic is needed |
| Can SAM conversion be used with any interface | No, the interface must have exactly one abstract method, and Kotlin interfaces must additionally be declared with fun interface |