Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 134 ยท Functions

Function Types and Type Aliases

Learn Kotlin function types: (A) -> B syntax, nullable and suspend types, function types with receivers, typealias, fun interface and SAM conversion, with runnable examples.

Every function in Kotlin has a type, just like every number or string does. The type of fun double(x: Int): Int is (Int) -> Int: "takes an Int, returns an Int". Once you can write that type down, you can store a function in a variable, put it in a list, pass it to another function or return it from one. You have been doing this since Lambdas and Higher-Order Functions; this lesson is about the type itself, and about the tools Kotlin gives you to keep long function types readable.

You will learn the full syntax of function types, how a receiver can be part of the type (the trick behind apply, buildString and every Kotlin DSL), how typealias gives a name to a type, and how fun interface lets you pass a lambda where an interface is expected.

Writing function types

A function type is a list of parameter types in parentheses, an arrow, and a return type:

Type Meaning
() -> Unit no parameters, returns nothing useful
(Int) -> Int one Int in, one Int out
(String, Int) -> Boolean two parameters
(Int) -> (Int) -> Int takes an Int, returns a function from Int to Int
((Int) -> Int)? a function that may be null (note the extra parentheses)

The return type is never optional. A function that returns nothing still writes -> Unit; you cannot leave the arrow out.

Kotlin Function types in variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints 49, 8, 42, called d and 15. Notice that a holds a reference to an existing function and b holds a lambda, yet both have exactly the same type. That is the point: the type describes what you can do with the value (call it with an Int, get an Int) and does not care how it was created.

Parameter names in function types

You may name parameters in a function type. The names are documentation only. They appear in IDE hints and make a long type readable, but the actual lambda can choose any names:

Kotlin
val discount: (price: Double, percent: Int) -> Double = { p, pct -> p * (100 - pct) / 100 }

The type of discount is still "a function of a Double and an Int returning a Double". Two function types with different parameter names but the same shapes are the same type.

Nullable function types and invoke

To make the whole function optional, wrap it in parentheses and add ?. Without the parentheses, the ? would make only the return type nullable:

Kotlin Optional callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is downloading a.txt, downloading b.txt, finished b.txt and null. In onDone?.invoke(name) the safe call skips the call when onDone is null. () -> Int? is a non-null function that returns Int?, while (() -> Int)? would be a nullable function. Mixing these up is a classic beginner mistake, so look at where the parentheses are.

Every function value has an invoke method, which is what f(x) really calls. Most of the time you never write .invoke yourself; you only need it for the safe call ?.invoke(...).

Function types with a receiver

A function type may start with a receiver type: String.(Int) -> String. Read it as "a function that is called on a String, takes an Int and returns a String". Inside a lambda of this type, this is the receiver, so you can call its members without a prefix.

Kotlin A lambda with a receiver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is hahaha (x3), hoho (x2) and DONE!. Both calling styles work: "ha".repeatWithCount(3) looks like a member call, and repeatWithCount("ho", 2) passes the receiver as the first argument. In shout, uppercase() means this.uppercase() because this is the string.

This is how the scope functions apply and with, and buildString, work. Here is a tiny version of buildString written from scratch:

Kotlin Writing your own builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints Kotlin 2 and 12. Inside the lambda passed to build, you can call append directly because the lambda's receiver is a StringBuilder. The next steps in the story are Type-Safe Builders and DSLs and Scope Functions.

A function type with a receiver and an ordinary function type with the receiver as the first parameter are interchangeable at run time. String.(Int) -> String and (String, Int) -> String are different Kotlin types, but a value of one fits where the other is expected. The receiver form only changes how you write the lambda and the call.

Suspend function types

A function type may be marked suspend, as in suspend (Int) -> String. Such a function can call other suspending functions and can only be called from a coroutine or another suspend function. You will meet it again in Suspend Functions. A suspend type and a plain one are not compatible: you cannot pass a regular lambda where suspend () -> Unit is expected without it being compiled as a suspending lambda, and vice versa.

Type aliases

Function types get long quickly. Compare these two signatures:

Kotlin
fun register(handler: (String, Map<String, List<String>>) -> Result<Boolean>) { }
fun register(handler: RequestHandler) { }

A type alias gives an existing type a second name. The second signature is easier to read and the name says what the function is for.

Kotlin typealias for function types and collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 2, [HELLO] and bo. The word Predicate<T> is a generic alias: it takes a type parameter just like a class would.

The most important fact about typealias is that it is only a name. It creates no new type. Predicate<String> and (String) -> Boolean are the same type for the compiler, and you can pass one wherever the other is expected. This is different from a value class, which creates a real, distinct type.

Kotlin An alias does not protect you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This compiles and prints user #99, although an order id is passed where a user id is expected. If you need the compiler to reject that mix-up, use a @JvmInline value class instead. Use an alias to improve readability, never for type safety.

A few more rules:

  • A type alias must be declared at the top level of a file (not inside a function or class).
  • It can have the same visibility modifiers as other declarations, e.g. private typealias.
  • It cannot be recursive and cannot add members. You cannot write fun Predicate.negate() as a member of a new type, but you can write extension functions on the underlying type.
  • Error messages and IDE tooltips often show the expanded type, not your alias.

Aliases for long generics and nested classes

Aliases are also handy for noisy generic types or to shorten a name that clashes with another one:

Kotlin
typealias Graph = Map<String, Set<String>>
typealias JavaList<T> = java.util.ArrayList<T>

SAM conversion and fun interface

Many Java APIs, and some Kotlin ones, expect an object of an interface that has a single abstract method (a SAM interface, "single abstract method"), such as Runnable or Comparator. Writing object : Runnable { override fun run() { ... } } is wordy. For Java interfaces Kotlin converts a lambda automatically, and for your own Kotlin interfaces you opt in with fun interface.

Kotlin fun interface and SAM conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is notBlank -> false, short -> true, running task and [a, bb, ccc]. Validator { ... } is the SAM constructor: the interface name followed by a lambda. The trailing lambda in check("short", "kotlin") { ... } is converted automatically because the parameter type is a fun interface.

A fun interface must have exactly one abstract method, but it may also have any number of non-abstract members. Without the fun keyword, an ordinary Kotlin interface is not SAM-convertible:

Kotlin A normal interface does not accept a lambda (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler rejects the lambda with main.kt:8:29: error: argument type mismatch: actual type is '() -> Boolean', but 'Validator' was expected., followed by unresolved reference 'it' because the lambda was treated as one without parameters. Either add fun before interface, or change the parameter to the function type (String) -> Boolean.

Function type or fun interface?

Both let a caller pass a lambda. Prefer the plain function type by default: it needs no extra declaration and works with every library function. Choose a fun interface when:

  • the concept deserves a name and documentation (Validator, EventListener);
  • you want to add default or helper methods to it;
  • you need to call it from Java or implement it from Java as a normal interface;
  • you want a distinct type, so two unrelated (String) -> Boolean functions cannot be mixed up.

Pitfalls

  • Lambdas are not comparable. Two lambdas with the same body are not equal; do not use them as map keys.
  • Return type inference. A lambda stored in a val without a declared type infers its parameter types only if you give them: val f = { x -> x * 2 } does not compile because x has no type. Write { x: Int -> x * 2 } or declare the variable's type.
  • Receiver confusion. Inside a lambda with a receiver, a name may resolve to the receiver or to an outer variable. When it matters, write this. or this@outer.
  • Overusing aliases. An alias hides the real type in code reviews. Keep them for long or repeated types.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of the function fun add(a: Int, b: Int): Int = a + b?

    The parameter types go in parentheses separated by commas, followed by an arrow and the return type.
  2. 2. Which type describes a function that may be null?

    Parentheses around the whole function type plus ? make the function itself nullable. () -> Int? is a non-null function returning a nullable Int.
  3. 3. What does a typealias create?

    An alias adds no type safety; UserId = Int and OrderId = Int are interchangeable with each other and with Int.
  4. 4. Inside a lambda of type StringBuilder.() -> Unit, what is this?

    The receiver type in a function type makes the receiver object available as this inside the lambda.
  5. 5. What must you add to an interface so a lambda can be passed where it is expected?

    Only fun interface declarations (with a single abstract method) support SAM conversion for Kotlin interfaces.

Summary

  • A function type is written (Params) -> Return; the return type is always required, Unit if nothing is returned.
  • Make a function optional with ((Int) -> Int)? and call it with ?.invoke(...).
  • Receiver.(Params) -> Return gives the lambda a this; it powers apply, with, buildString and DSLs.
  • suspend function types can call suspending functions.
  • typealias gives a type a readable name but creates no new type and no extra safety.
  • fun interface lets lambdas stand in for your own single-method interfaces; Java SAM interfaces convert automatically.

Next: Collections Overview