Functions

Function declarations

Functions in Kotlin are declared using the fun keyword:

  1. fun double(x: Int): Int {
  2. return 2 * x
  3. }

Function usage

Calling functions uses the traditional approach:

  1. val result = double(2)

Calling member functions uses the dot notation:

  1. Stream().read() // create instance of class Stream and call read()

Parameters

Function parameters are defined using Pascal notation, i.e. name: type. Parameters are separated using commas. Each parameter must be explicitly typed:

  1. fun powerOf(number: Int, exponent: Int): Int { /*...*/ }

You can use a trailing comma when you declare function parameters:

  1. fun powerOf(
  2. number: Int,
  3. exponent: Int, // trailing comma
  4. ) { /*...*/ }

Default arguments

Function parameters can have default values, which are used when you skip the corresponding argument. This reduces a number of overloads compared to other languages:

  1. fun read(
  2. b: Array<Byte>,
  3. off: Int = 0,
  4. len: Int = b.size,
  5. ) { /*...*/ }

A default value is defined using the = after the type.

Overriding methods always use the same default parameter values as the base method. When overriding a method with default parameter values, the default parameter values must be omitted from the signature:

  1. open class A {
  2. open fun foo(i: Int = 10) { /*...*/ }
  3. }
  4. class B : A() {
  5. override fun foo(i: Int) { /*...*/ } // No default value is allowed
  6. }

If a default parameter precedes a parameter with no default value, the default value can only be used by calling the function with named arguments:

  1. fun foo(
  2. bar: Int = 0,
  3. baz: Int,
  4. ) { /*...*/ }
  5. foo(baz = 1) // The default value bar = 0 is used

If the last argument after default parameters is a lambda, you can pass it either as a named argument or outside the parentheses:

  1. fun foo(
  2. bar: Int = 0,
  3. baz: Int = 1,
  4. qux: () -> Unit,
  5. ) { /*...*/ }
  6. foo(1) { println("hello") } // Uses the default value baz = 1
  7. foo(qux = { println("hello") }) // Uses both default values bar = 0 and baz = 1
  8. foo { println("hello") } // Uses both default values bar = 0 and baz = 1

Named arguments

When calling a function, you can name one or more of its arguments. This may be helpful when a function has a large number of arguments, and it’s difficult to associate a value with an argument, especially if it’s a boolean or null value.

When you use named arguments in a function call, you can freely change the order they are listed in, and if you want to use their default values you can just leave them out altogether.

Consider the following function reformat() that has 4 arguments with default values.

  1. fun reformat(
  2. str: String,
  3. normalizeCase: Boolean = true,
  4. upperCaseFirstLetter: Boolean = true,
  5. divideByCamelHumps: Boolean = false,
  6. wordSeparator: Char = ' ',
  7. ) {
  8. /*...*/
  9. }

When calling this function, you don’t have to name all its arguments:

  1. reformat(
  2. 'String!',
  3. false,
  4. upperCaseFirstLetter = false,
  5. divideByCamelHumps = true,
  6. '_'
  7. )

You can skip all arguments with default values:

  1. reformat('This is a long String!')

You can skip some arguments with default values. However, after the first skipped argument, you must name all subsequent arguments:

  1. reformat('This is a short String!', upperCaseFirstLetter = false, wordSeparator = '_')

You can pass a variable number of arguments (vararg) with names using the spread operator:

  1. fun foo(vararg strings: String) { /*...*/ }
  2. foo(strings = *arrayOf("a", "b", "c"))

On the JVM: You can’t use the named argument syntax when calling Java functions because Java bytecode does not always preserve names of function parameters.

Unit-returning functions

If a function does not return any useful value, its return type is Unit. Unit is a type with only one value - Unit. This value does not have to be returned explicitly:

  1. fun printHello(name: String?): Unit {
  2. if (name != null)
  3. println("Hello $name")
  4. else
  5. println("Hi there!")
  6. // `return Unit` or `return` is optional
  7. }

The Unit return type declaration is also optional. The above code is equivalent to:

  1. fun printHello(name: String?) { ... }

Single-expression functions

When a function returns a single expression, the curly braces can be omitted and the body is specified after a \= symbol:

  1. fun double(x: Int): Int = x * 2

Explicitly declaring the return type is optional when this can be inferred by the compiler:

  1. fun double(x: Int) = x * 2

Explicit return types

Functions with block body must always specify return types explicitly, unless it’s intended for them to return Unit, in which case it is optional. Kotlin does not infer return types for functions with block bodies because such functions may have complex control flow in the body, and the return type will be non-obvious to the reader (and sometimes even for the compiler).

Variable number of arguments (Varargs)

A parameter of a function (normally the last one) may be marked with vararg modifier:

  1. fun <T> asList(vararg ts: T): List<T> {
  2. val result = ArrayList<T>()
  3. for (t in ts) // ts is an Array
  4. result.add(t)
  5. return result
  6. }

allowing a variable number of arguments to be passed to the function:

  1. val list = asList(1, 2, 3)

Inside a function a vararg-parameter of type T is visible as an array of T, i.e. the ts variable in the example above has type Array<out T>.

Only one parameter may be marked as vararg. If a vararg parameter is not the last one in the list, values for the following parameters can be passed using the named argument syntax, or, if the parameter has a function type, by passing a lambda outside parentheses.

When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *):

  1. val a = arrayOf(1, 2, 3)
  2. val list = asList(-1, 0, *a, 4)

Infix notation

Functions marked with the infix keyword can also be called using the infix notation (omitting the dot and the parentheses for the call). Infix functions must satisfy the following requirements:

  1. infix fun Int.shl(x: Int): Int { ... }
  2. // calling the function using the infix notation
  3. 1 shl 2
  4. // is the same as
  5. 1.shl(2)

Infix function calls have lower precedence than the arithmetic operators, type casts, and the rangeTo operator. The following expressions are equivalent:

  • 1 shl 2 + 3 is equivalent to 1 shl (2 + 3)
  • 0 until n * 2 is equivalent to 0 until (n * 2)
  • xs union ys as Set<*> is equivalent to xs union (ys as Set<*>)

On the other hand, infix function call’s precedence is higher than that of the boolean operators && and ||, is- and in-checks, and some other operators. These expressions are equivalent as well:

  • a && b xor c is equivalent to a && (b xor c)
  • a xor b in c is equivalent to (a xor b) in c

See the Grammar reference for the complete operators precedence hierarchy.

Note that infix functions always require both the receiver and the parameter to be specified. When you’re calling a method on the current receiver using the infix notation, you need to use this explicitly; unlike regular method calls, it cannot be omitted. This is required to ensure unambiguous parsing.

  1. class MyStringCollection {
  2. infix fun add(s: String) { /*...*/ }
  3. fun build() {
  4. this add "abc" // Correct
  5. add("abc") // Correct
  6. //add "abc" // Incorrect: the receiver must be specified
  7. }
  8. }

Function scope

In Kotlin, functions can be declared at top level in a file, meaning you do not need to create a class to hold a function, which you are required to do in languages such as Java, C# or Scala. In addition to top level functions, Kotlin functions can also be declared local, as member functions and extension functions.

Local functions

Kotlin supports local functions, i.e. a function inside another function:

  1. fun dfs(graph: Graph) {
  2. fun dfs(current: Vertex, visited: MutableSet<Vertex>) {
  3. if (!visited.add(current)) return
  4. for (v in current.neighbors)
  5. dfs(v, visited)
  6. }
  7. dfs(graph.vertices[0], HashSet())
  8. }

Local function can access local variables of outer functions (i.e. the closure), so in the case above, the visited can be a local variable:

  1. fun dfs(graph: Graph) {
  2. val visited = HashSet<Vertex>()
  3. fun dfs(current: Vertex) {
  4. if (!visited.add(current)) return
  5. for (v in current.neighbors)
  6. dfs(v)
  7. }
  8. dfs(graph.vertices[0])
  9. }

Member functions

A member function is a function that is defined inside a class or object:

  1. class Sample {
  2. fun foo() { print("Foo") }
  3. }

Member functions are called with dot notation:

  1. Sample().foo() // creates instance of class Sample and calls foo

For more information on classes and overriding members see Classes and Inheritance.

Generic functions

Functions can have generic parameters which are specified using angle brackets before the function name:

  1. fun <T> singletonList(item: T): List<T> { /*...*/ }

For more information on generic functions see Generics.

Inline functions

Inline functions are explained here.

Extension functions

Extension functions are explained in their own section.

Higher-order functions and lambdas

Higher-Order functions and Lambdas are explained in their own section.

Tail recursive functions

Kotlin supports a style of functional programming known as tail recursion. This allows some algorithms that would normally be written using loops to instead be written using a recursive function, but without the risk of stack overflow. When a function is marked with the tailrec modifier and meets the required form, the compiler optimizes out the recursion, leaving behind a fast and efficient loop based version instead:

  1. val eps = 1E-10 // "good enough", could be 10^-15
  2. tailrec fun findFixPoint(x: Double = 1.0): Double =
  3. if (Math.abs(x - Math.cos(x)) < eps) x else findFixPoint(Math.cos(x))

This code calculates the fixpoint of cosine, which is a mathematical constant. It simply calls Math.cos repeatedly starting at 1.0 until the result doesn’t change any more, yielding a result of 0.7390851332151611 for the specified eps precision. The resulting code is equivalent to this more traditional style:

  1. val eps = 1E-10 // "good enough", could be 10^-15
  2. private fun findFixPoint(): Double {
  3. var x = 1.0
  4. while (true) {
  5. val y = Math.cos(x)
  6. if (Math.abs(x - y) < eps) return x
  7. x = Math.cos(x)
  8. }
  9. }

To be eligible for the tailrec modifier, a function must call itself as the last operation it performs. You cannot use tail recursion when there is more code after the recursive call, and you cannot use it within try/catch/finally blocks. Currently, tail recursion is supported by Kotlin for JVM and Kotlin/Native.