Skip to content

Functions and lambdas

fun, a name, parameters with types, and the type it gives back after :.

fun reward(level: Int): Int {
return level * 10
}
val coins = reward(5)

A function that is one expression can use =. Its return type can be left out.

fun reward(level: Int) = level * 10

A function with no return type gives back Unit, meaning nothing.

fun announce(text: String) {
Logger.info("Announcement: $text")
}

A parameter can have a default, used when the caller leaves it out.

fun spawnWave(size: Int, boss: Boolean = false) =
if (boss) "$size goblins and a boss" else "$size goblins"
val easy = spawnWave(3)
val hard = spawnWave(5, true)

A caller can name the arguments, in any order.

fun trade(item: String, price: Int, quantity: Int = 1) = "$quantity x $item for $price"
val offer = trade(price = 50, item = "lobster")

vararg takes any number of arguments of one type.

fun total(vararg prices: Int) = prices.sum()
val bill = total(4, 20, 50)

fun Type.name() adds a function to a type you didn’t write. Inside, this is the value.

fun Int.asCoins() = "$this coins"
val label = 250.asCoins()

An infix function of one parameter can be called without the dot and brackets.

infix fun String.costs(price: Int) = "$this: $price coins"
val tag = "lobster" costs 50

An operator function gives a type its own +, -, [] and others.

class Coins(val amount: Int) {
operator fun plus(other: Coins) = Coins(amount + other.amount)
}
val purse = Coins(10) + Coins(5)

A type parameter in <> lets one function work with any type.

fun <T> pickOne(options: List<T>): T = options.random()
val drop = pickOne(listOf("bones", "coins", "gem"))

A function can be declared inside another one.

fun describeParty(names: List<String>): String {
fun tag(name: String) = "[$name]"
return names.joinToString(" ") { tag(it) }
}

A lambda is a block of code you can pass around, written in { }. Parameters come before ->.

val double = { n: Int -> n * 2 }
val result = double(21)

A lambda with one parameter can leave it out and call it it.

val prices = listOf(4, 50, 20)
val cheap = prices.filter { it < 30 }

When the last argument is a lambda, it can go after the brackets. With no other arguments, the brackets go too. Hooks are written this way.

val names = listOf("Ana", "Bo")
val greeted = names.map { "Hello, $it" }
on_login { player ->
player.message("Welcome.")
}

(Int) -> String is the type of a function from Int to String. A function can take one as a parameter.

fun repeatFor(times: Int, action: (Int) -> Unit) {
for (n in 1..times) action(n)
}
repeatFor(3) { Logger.info("Round $it") }

::name refers to a function without calling it.

fun isRare(item: String) = item.startsWith("dragon")
val rare = listOf("dragon bones", "bones").filter(::isRare)

let, apply, also, run and with run a block with a value at hand. apply sets things up and gives back the value.

class Shop(val name: String) {
var stock = 0
var open = false
}
val store = Shop("General store").apply {
stock = 40
open = true
}
val summary = with(store) { "$name has $stock items" }