Author profile picture

First-Class Function

A programming language that supports first-class functions allows you to:

  1. Assign a function to a variable
  2. Pass a function to another function as an argument
  3. Return a function from another function as a result

Kotlin allows you to do all three of these.

Assigning Functions

There are a few different ways that you can assign a function to a variable in Kotlin.

Anonymous Function

val add = fun(a: Int, b: Int) = a + b

Lambda

val subtract = { a: Int, b: Int -> a - b }

Function Reference

If the method already exists, you can assign it by means of a function reference

fun doMultiply(a: Int, b: Int) = a * b
val multiply = ::doMultiply

Functions as Arguments and Results

For examples of passing a function as an argument or a result, see higher-order function.

Share this article:

  • Share on Twitter
  • Share on Facebook
  • Share on Reddit