Functions, Lambdas & Extensions

Default and named arguments, single-expression functions, extension functions, lambdas and function references.

Kotlin functions are concise and flexible: default arguments replace overloads, named arguments make calls readable, extension functions add methods to existing types, and lambdas make functions first-class values.

Functions in practice

connect has defaults for baud, parity and stop bits; callers pass only what differs, by name in any order.

celsiusToF is a single-expression function with an inferred return type.

String.isHexId() is an extension function: called like a member, without modifying String.

measure takes a lambda (Int) -> Double; a lambda passed last can go outside the parentheses.::celsiusToF is a function reference, passed to map.

Writing four overloads of connect for every combination of optional settings

One function with default parameter values Defaults and named arguments cover all combinations with one definition; add @JvmOverloads if Java callers need overloads.

What is an extension function?

A function declared outside a class (fun Type.name()) that can be called like a member of that type. It cannot access private members and is resolved statically.