Kotlin·Kotlin from syntax to a coroutine app

Functions and lambdas

Use default arguments, named arguments and higher-order functions.

Beginner 12 min read Lesson 3 of 300 Challenge included
What you will be able to do
  • Use default arguments instead of overloads.
  • Use named arguments for clarity.
  • Pass lambdas as the last parameter.
  • Use function references with ::.

In plain English

Functions are values. Lambdas and function references let you pass behaviour. Default and named arguments remove overload boilerplate and make call sites readable.

Functions.ktKotlin
fun format(minutes: Int, suffix: String = "min") = "$minutes $suffix"

fun applyTwice(value: Int, transform: (Int) -> Int): Int = transform(transform(value))

fun main() {
    println(format(12))
    println(applyTwice(3) { it * 2 })
}
Your turn

Write a trailing lambda

Easy

Call applyTwice(2) with a lambda that adds one.

KOTLIN · starter
applyTwice(2)
Check your understanding before moving on.
Knowledge checkQuestion 1

What does a higher-order function accept?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Collections
Lesson 3 of 300 · 0% of course