Give the parameter a function type and pass a lambda: fun calculate(a: Int, b: Int, op: (Int, Int) -> Int) = op(a, b), then call calculate(6, 3) { x, y -> x * y }. To pass a function you already have, use a reference with ::: list.filter(::isAdult), names.map(String::uppercase) or list.map(::User) for a constructor.
In Kotlin a function is a value like any other: it has a type, such as (String) -> Int, it can sit in a variable, go into another function as an argument and come back out as a result. Java needs a functional interface such as Function<Integer, Integer> for this; Kotlin writes the type directly. The sections below cover function types and lambdas (with the trailing lambda syntax and it), what :: means for functions, methods and constructors, functions that return functions, optional callbacks, fun interface and passing a lambda where an interface is expected, and the compile error you get when the interface is not a fun interface, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1Function types, lambdas and the trailing lambdaRecommended
Declare the parameter with a function type: the parameter types in parentheses, an arrow, and the return type. (Int, Int) -> Int takes two Ints and returns one; (Int) -> Unit returns nothing useful; () -> Boolean takes nothing. Inside the function you call the parameter like any function. At the call site you pass a lambda, { x, y -> x + y }. When the lambda is the last argument it can go after the parentheses (a trailing lambda), and when it is the only argument the parentheses go away. A lambda with one parameter can skip naming it and use it. There is no return in a lambda: its last expression is the result.
// (Int, Int) -> Int is the type: two Ints in, one Int out fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int = operation(a, b) // (Int) -> Unit: takes an Int, returns nothing useful fun repeatAction(times: Int, action: (Int) -> Unit) { for (i in 1..times) action(i) } fun main() { // Pass a lambda in the parentheses println(calculate(6, 3, { x, y -> x + y })) // Trailing lambda: the last argument moves outside () println(calculate(6, 3) { x, y -> x * y }) // A lambda can be stored in a val and passed by name val subtract: (Int, Int) -> Int = { x, y -> x - y } println(calculate(6, 3, subtract)) // One parameter: it is its implicit name repeatAction(3) { println("step $it") } // The last expression in a lambda is its return value val words = listOf("kiwi", "banana", "fig") val lengths = words.map { word -> val n = word.length "$word=$n" } println(lengths) // The lambda is the only argument: no () needed println(words.filter { it.length > 3 }) println(words.sortedBy { it.length }) }
Output
The same calculate gives 9, 18 and 3 depending on the lambda you hand it. The first two calls are the same thing written two ways: the trailing form is what you will see almost everywhere, and it is why map { … }, filter { … } and sortedBy { … } read like built-in syntax. They are ordinary functions that take a function. The map block has two lines and returns the last one, giving [kiwi=4, banana=6, fig=3]. A bare return inside a lambda leaves the enclosing function, not the lambda; to leave only the lambda, write return@map, covered in break out of nested loops.
2Function references: what :: means
:: turns an existing function into a value without calling it, so you can pass it where a function type is expected. ::isAdult refers to a top-level function. String::uppercase refers to a method of a class; the object it runs on becomes the first parameter, so its type is (String) -> String. hello::greet is a bound reference: it remembers the object hello, so only the method's own parameters are left. ::User is a constructor reference (Kotlin has no new, so a constructor is just a function named after the class), and User::name refers to a property.
data class User(val name: String, val age: Int) data class Tag(val label: String) class Greeter(private val greeting: String) { fun greet(name: String): String = "$greeting, $name!" } fun isAdult(age: Int): Boolean = age >= 18 fun main() { val ages = listOf(12, 18, 40) // ::name refers to a top-level function without calling it println(ages.filter(::isAdult)) val check: (Int) -> Boolean = ::isAdult println(check(17)) ages.take(1).forEach(::println) // Class::method: the object becomes the first parameter val names = listOf("ada", "linus") println(names.map(String::uppercase)) val upper: (String) -> String = String::uppercase println(upper("grace")) // obj::method: a bound reference remembers its object val hello = Greeter("Hello") println(names.map(hello::greet)) // ::Class is a constructor reference println(listOf("kotlin", "jvm").map(::Tag)) val users = listOf("Ada", "Linus").zip(listOf(36, 21), ::User) println(users) // Class::property works the same way println(users.map(User::name)) println(users.sumOf(User::age)) }
Output
ages.filter(::isAdult) is the same as ages.filter { isAdult(it) } and keeps [18, 40]. forEach(::println) works even though println has many overloads: the expected type picks the right one. The bound hello::greet prints Hello, ada! for each name, and zip(…, ::User) passes the two-argument constructor as the function that combines each pair, giving [User(name=Ada, age=36), User(name=Linus, age=21)]. If you know Java, :: is the same idea as a method reference like String::toUpperCase or User::new; inside a class, this::method passes one of your own methods.
3Return a function from a function
A function type works as a return type too: fun multiplier(factor: Int): (Int) -> Int builds and returns a new function, and the lambda it returns keeps factor after multiplier has finished (a closure). Call the result like any function, or with .invoke(…), which is what the call syntax turns into. When a function type gets long, a typealias gives it a name. An anonymous function, fun(n: Int): String { … }, is the alternative to a lambda when you want a declared return type or several return statements.
// The return type is a function type: (Int) -> Int fun multiplier(factor: Int): (Int) -> Int = { it * factor } // Takes two functions and returns a new one that runs both fun <A, B, C> compose(f: (A) -> B, g: (B) -> C): (A) -> C = { x -> g(f(x)) } // A typealias gives a long function type a short name typealias Op = (Int, Int) -> Int fun main() { val double = multiplier(2) val triple = multiplier(3) println(double(5)) println(triple.invoke(5)) println(listOf(1, 2, 3).map(triple)) // Call the returned function straight away println(multiplier(10)(4)) val trimmedLength = compose(String::trim, String::length) println(trimmedLength(" hi ")) // An anonymous function: declared return type, plain return val parity = fun(n: Int): String { if (n % 2 == 0) return "even" return "odd" } println(listOf(1, 2).map(parity)) // Functions stored in a map and picked by name val ops: Map<String, Op> = mapOf( "+" to { a, b -> a + b }, "-" to { a, b -> a - b }, "max" to ::maxOf, ) for ((name, op) in ops) println("$name: ${op(7, 4)}") println(ops.getValue("+")(1, 2)) }
Output
double and triple are two functions made by the same multiplier, each with its own factor: 10 and 15. multiplier(10)(4) calls the result at once and gives 40. compose(String::trim, String::length) trims first, then counts, so " hi " gives 2. In the anonymous function, return leaves only that function, which is the main difference from a lambda. The map of operations shows functions as plain data: ::maxOf sits next to two lambdas because all three fit Op.
4Optional callbacks: nullable function types and ?.invoke
For a callback the caller may leave out, make the type nullable. The function type needs parentheses around it: ((Int) -> Unit)?, because (Int) -> Unit? would mean a function that returns Unit?. Call it with ?.invoke(…), which does nothing when it is null. Calling it directly doesn't compile; here the error reads Reference has a nullable type '((Int) -> Unit)?'. Use explicit '?.invoke' to make a function-like call instead. Often a default value is simpler than null: onFail: (Int) -> Unit = {} lets callers skip the argument and needs no null check.
class Downloader { // A nullable function type needs parentheses around it var onProgress: ((Int) -> Unit)? = null fun download(name: String, onDone: ((String) -> Unit)? = null) { for (pct in listOf(50, 100)) { // ?.invoke calls it only when one was set onProgress?.invoke(pct) } onDone?.invoke("$name saved") } } // A default lambda instead of null: callers may skip it fun retry(times: Int, onFail: (Int) -> Unit = {}, block: () -> Boolean) { for (attempt in 1..times) { if (block()) return onFail(attempt) } } fun main() { val d = Downloader() d.download("a.txt") println("no callbacks set, nothing printed") d.onProgress = { println("progress $it%") } d.download("b.txt") { println(it) } // A nullable function value: if (f != null) f(x) works too val log: ((String) -> Unit)? = ::println if (log != null) log("smart cast, called directly") var calls = 0 retry(3, onFail = { println("attempt $it failed") }) { ++calls == 3 } retry(2) { true } println("calls: $calls") }
Output
The first download has no callbacks, so it prints nothing. After onProgress is set, the second prints progress 50%, progress 100% and b.txt saved. On a local val, if (log != null) smart-casts and log(…) works; on a var property like onProgress the same check doesn't compile (Smart cast to '(Int) -> Unit' is impossible, because 'onProgress' is a mutable property that could be mutated concurrently.), so ?.invoke is the way there. retry(2) { true } uses the default {} and needs no callback at all.
5fun interface, SAM conversion and object expressions
Sometimes the parameter is an interface, not a function type. If the interface has exactly one abstract method and is declared fun interface (Kotlin 1.4 and later), you can pass a lambda and Kotlin builds the object for you; this is SAM (single abstract method) conversion. Java interfaces with one method, such as Runnable and Comparator, get it without any keyword. For an interface with several methods, or when you need state, write an object expression, object : ClickListener { … }. It is Kotlin's answer to Java's anonymous class new ClickListener() { … }.
// fun interface: one abstract method, so a lambda can stand in for it fun interface PriceRule { fun apply(price: Double): Double } // A plain interface with two methods: use an object expression interface ClickListener { fun onClick(x: Int) fun onLongClick(x: Int) } fun checkout(price: Double, rule: PriceRule): Double = rule.apply(price) fun main() { // SAM conversion: pass a lambda where a PriceRule is expected println(checkout(80.0) { it * 0.9 }) // Or build one with the interface name in front of the lambda val freeOver100 = PriceRule { if (it > 100) 0.0 else it } println(checkout(150.0, freeOver100)) // Anonymous object: Java's "new ClickListener() { ... }" val listener = object : ClickListener { var clicks = 0 override fun onClick(x: Int) { clicks++ println("click at $x") } override fun onLongClick(x: Int) = println("long click at $x") } listener.onClick(10) listener.onLongClick(20) println("clicks: ${listener.clicks}") // Java interfaces with one method take lambdas too val task = Runnable { println("running") } task.run() val byLength = Comparator<String> { a, b -> a.length - b.length } println(listOf("banana", "fig", "kiwi").sortedWith(byLength)) val t = Thread { println("in a thread") } t.start() t.join() }
Output
checkout(80.0) { it * 0.9 } passes a plain lambda where a PriceRule is expected and gives 72.0. PriceRule { … } does the same when there is no parameter type to go by, such as a val. The object expression implements both methods and keeps its own clicks counter, which you can read because listener is a local value: clicks: 1. Runnable { … }, Comparator<String> { … } and Thread { … } are the conversions to Java interfaces you will meet most (with Thread, a class, the lambda becomes the Runnable its constructor takes). When you design your own API in Kotlin, a function type such as (Double) -> Double is the lighter choice; a fun interface pays off when the type deserves a name, extra default methods, or Java callers.
6The compile error: a lambda for a plain interface
Drop the fun from section 5's interface and the same call stops compiling. Kotlin only converts a lambda to a Kotlin interface declared as fun interface, so for a plain interface the lambda is just a lambda, and it doesn't fit the parameter type. This is the error behind "passing a lambda instead of an interface".
// A plain interface: no "fun" in front interface PriceRule { fun apply(price: Double): Double } fun checkout(price: Double, rule: PriceRule): Double = rule.apply(price) fun main() { println(checkout(80.0) { it * 0.9 }) }
Output
The compiler stops with Argument type mismatch: actual type is '() -> ??? (Unknown lambda return type)', but 'PriceRule' was expected. followed by Unresolved reference 'it'. There are three fixes: write fun interface PriceRule if you own the interface; pass an object expression, checkout(80.0, object : PriceRule { override fun apply(price: Double) = price * 0.9 }); or change the parameter to a function type, rule: (Double) -> Double. Writing PriceRule { … } on a plain interface fails as well, with Interface 'interface PriceRule : Any' does not have constructors.
7Which should you use?
| Form | Example | Best for |
|---|---|---|
| Function type + lambda | op: (Int, Int) -> Int | Most parameters that take behavior |
| Function reference | ::isAdult, String::trim, ::User | Passing a function that already exists |
| Returned function | fun multiplier(n: Int): (Int) -> Int | Building functions from settings |
| Nullable or default callback | ((Int) -> Unit)? or = {} | Callbacks a caller may leave out |
| fun interface | fun interface PriceRule | A named type, Java callers, still lambda-friendly |
| object : Interface { … } | object : ClickListener { … } | Interfaces with several methods, or state |
Frequently asked questions
How do I pass a function as a parameter in Kotlin?
Declare the parameter with a function type, such as op: (Int, Int) -> Int, and call it inside like any function: op(a, b). Callers pass a lambda, calculate(6, 3) { x, y -> x * y }, or a reference to an existing function, calculate(6, 3, ::maxOf). No interface is needed.
What does :: mean in Kotlin?
:: makes a reference: a function, property or constructor used as a value instead of being called. ::isAdult is a top-level function, String::length a member of a class (the object becomes the first parameter), user::greet a method bound to one object, and ::User the constructor. Pass any of them where a matching function type is expected. User::class is a different use of ::: it gives the KClass of the type.
Are there constructor references in Kotlin?
Yes. ::User refers to the constructor of User and has a function type matching its parameters, for example (String, Int) -> User. So names.map(::Tag) builds one Tag per name, and names.zip(ages, ::User) builds users from two lists. It is the Kotlin form of Java's User::new.
How do I create an instance of an anonymous interface in Kotlin?
Use an object expression: val listener = object : ClickListener { override fun onClick(x: Int) { … } }. It replaces Java's new ClickListener() { … } and can implement several methods and hold state. If the interface has a single abstract method and is a fun interface (or a Java interface such as Runnable), a lambda is shorter: Runnable { println("running") }.
What is a trailing lambda?
When the last parameter of a function has a function type, the lambda can go after the closing parenthesis: calculate(6, 3) { x, y -> x * y } instead of calculate(6, 3, { x, y -> x * y }). If the lambda is the only argument, drop the parentheses too: list.filter { it > 0 }. Inside a lambda with one parameter, it names that parameter.
Should a function that takes a lambda be inline?
Mark it inline when the lambda is called during the call and the function is small or called often, as map, filter and forEach in the standard library are. The compiler then copies the function body and the lambda into each call site, so no function object is created, and a bare return in the lambda can leave the caller. Don't inline a function that stores the lambda for later, such as a callback property: that fails with Illegal usage of inline parameter unless the parameter is marked noinline.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground