Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 134 ยท Functions

Functions

Learn how to declare Kotlin functions - fun, parameters, return types, single-expression bodies, Unit, top-level functions and common compiler errors, with runnable examples.

A function is a named piece of code you can run as often as you like, with different inputs each time. You have already written one: fun main(). In this lesson you will learn the whole shape of a Kotlin function declaration, how values go in through parameters and come out through the return type, and why Kotlin lets you write many functions in a single line.

Functions are the main building block of Kotlin programs. Unlike Java, Kotlin does not force them to live inside a class: you can write them directly in a file, which keeps small programs short and makes utilities easy to share. Everything in the rest of this section (default arguments, lambdas, extension functions) builds on what you see here.

Declaring a function

A function declaration has five parts: the keyword fun, a name, a parameter list in parentheses, an optional return type after a colon, and a body in braces.

Kotlin Your first own function

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.

Read the first line from left to right: "a function called add, taking an Int named a and an Int named b, returning an Int." Every parameter needs an explicit type, written after its name with a colon. This is the opposite order to Java and C, and it is the same order you already know from val name: String.

Calling a function means writing its name and giving it arguments in the same order as the parameters. The vocabulary is worth keeping straight: parameters are the names in the declaration (a, b), arguments are the values you pass when calling (3, 4). A call such as add(1, 2) is itself an expression with the function's return type, so you can store it in a variable or pass it straight into another call, as the last line does.

Where functions can live

A function written outside any class is a top-level function. It belongs to the file (and package) rather than to an object, and you call it by name. There is no static keyword in Kotlin because you rarely need one. A function inside a class is a member function, called on an instance with a dot, like text.uppercase(). A function inside another function is a local function.

Names follow the usual convention: lowerCamelCase, starting with a verb when the function does something (sendEmail, parsePort) and with a noun or adjective when it computes a value (area, isEmpty).

Parameters are read-only

Inside a function, each parameter behaves like a val. You can read it, but you cannot assign a new value to it. That is a deliberate choice: when you read a function, you never have to wonder whether its input has been changed halfway through.

Kotlin Parameters cannot be reassigned (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 answers main.kt:2:5: error: 'val' cannot be reassigned. The fix is to compute a new value and return it, or to copy the parameter into a local var if you truly need a mutable working copy:

Kotlin
fun bump(n: Int): Int = n + 1

Note that "read-only" is about the name, not the object. If a parameter refers to a mutable list, you can still call add on that list. Only the parameter itself cannot point somewhere else.

Return types and the return statement

A function with a block body ({ ... }) that returns a value must say so with return, and its return type must be written explicitly. The compiler checks that every path through the function returns something of that type.

Kotlin Missing return on one path (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.

You get main.kt:3:1: error: missing return statement. with the caret under the closing brace: if x is not positive, the function runs off its end without a value. Handle the other cases, here with a when expression:

Kotlin Returning on every path

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.

return ends the function immediately, so the code after if (x > 0) return 1 only runs for non-positive numbers. This style, called early return, keeps code flat: handle the special cases first, then let the main logic run without extra nesting.

A mismatched argument is caught at the call site, not at run time. This is Kotlin's static typing at work:

Kotlin Wrong argument type (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 error is main.kt:4:17: error: argument type mismatch: actual type is 'String', but 'Int' was expected. The caret marks the offending argument "1". Kotlin never converts a String to an Int for you.

Single-expression functions

When the whole body is one expression, you can drop the braces and the return, and write = instead. This is a single-expression function:

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

In this form Kotlin can infer the return type from the expression, so you may leave it out, as the previous example did with fun add(a: Int, b: Int) = a + b. Because if, when and try are expressions, they work here too:

Kotlin Single-expression functions

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 standard library already has maxOf(a, b), so in real projects you would not write max yourself; it is here to show an if expression as a body.

When to write the return type anyway

Inference is convenient, but there are two rules to know:

  1. Block bodies with a result need an explicit return type. Kotlin does not infer return types for { ... } bodies. If you omit it, the function is treated as returning Unit.
  2. Public APIs should state their return type. A written type is documentation, and it protects you from accidentally changing the type of an exported function by editing its body. Recursive functions also need an explicit type, because the compiler cannot infer a type that depends on itself.

A good habit: infer for small private helpers, write the type for anything other code depends on.

Functions that return nothing useful: Unit

If a function has nothing useful to return, its return type is Unit, and you may leave it out. A block body then needs no return. This is the same Unit you met in Any, Unit and Nothing.

Kotlin Unit functions

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.

logIt has an expression body whose type is that of println, which is Unit. The last line prints kotlin.Unit: the call really is an expression with a value, just not an interesting one.

Naming what a function does

Good functions do one thing and are named for it. When you struggle to name a function without using "and", it probably does two things and wants to be split. Three small guidelines:

  • Pure functions first. A function that depends only on its parameters and returns a result (like square) is the easiest to test and to reason about.
  • Keep parameter lists short. More than three or four parameters is a hint to group related ones in a class, or to use default and named arguments.
  • Return values instead of printing. fun total(...): Int can be reused, tested and combined. fun printTotal(...) can only print. Print in main, compute in helpers.
Kotlin Small functions that combine

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.

Each function is tiny and testable on its own, and main reads like a description of what the program does.

Performance and design notes

A function call in Kotlin on the JVM is cheap, and the JIT compiler routinely inlines small ones. You do not need to write one giant function to be fast. Top-level functions compile into static methods of a class named after the file: a file main.kt becomes the class MainKt, which you can see in stack traces such as at MainKt.main(main.kt:10). Java code calls them like MainKt.add(1, 2).

When a function grows past one screen, look for a comment or a blank line that separates two ideas. That line is usually where a new function with a descriptive name wants to start.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the correct declaration of a function that returns the sum of two Ints?

    Kotlin uses the keyword fun, then name, parameters written as name: Type, and an optional return type after a colon. A single expression can follow an equals sign.
  2. 2. What happens if you write n = n + 1 inside a function whose parameter is n?

    Function parameters are read-only, like val. Compute a new value or copy the parameter into a local var.
  3. 3. Which return type does fun log(m: String) { println(m) } have?

    A function with a block body and no declared return type returns Unit, the type with exactly one value.
  4. 4. When must you write the return type explicitly?

    Kotlin infers the return type only for single-expression functions. A block body that returns a value needs its type written out, and so do recursive functions.
  5. 5. What does the compiler report for fun f(x: Int): Int { if (x > 0) return 1 }?

    When x is not positive the function reaches its end without returning an Int, so the compiler reports 'missing return statement'.

Summary

  • Declare functions with fun name(param: Type, ...): ReturnType { ... }; they can be top-level, members of a class, or local.
  • Parameters are read-only; arguments must match parameter types exactly, and mismatches are compile errors.
  • A block body needs an explicit return type and a return on every path; the compiler reports missing return statement otherwise.
  • A single-expression function uses = expression and can infer its return type; if, when and try work as that expression.
  • Functions without a useful result return Unit, which you may leave out.
  • Prefer small, pure functions that return values over functions that print.

Next: Default and Named Arguments