All lessons

Functions

9 min · Kotlin

Package code under a name so you can reuse it.

Kotlin · Functions0/5 cleared

Enemy 1 of 5

A function packages a piece of logic under a name, so you can reuse it instead of retyping the same code everywhere you need it. You've already used one without realizing it: fun main() is a function too — Kotlin just calls it automatically when the program starts. You define your own functions the same way, with fun, anywhere in the file.

Kotlin functions declare each parameter's type as name: Type, and — if the function returns a value — the return type follows the parameter list after a colon: fun double(n: Int): Int. This reads as "a function named double, taking one Int parameter n, returning an Int." Kotlin won't guess these types for you at a function's boundary (even though it happily infers types for local variables), which is a deliberate tradeoff: it lets the compiler catch a whole class of mistakes, like accidentally passing text where a number is expected, before the program ever runs.

return sends a value back to the caller and immediately exits the function — any code after it in that block won't execute. Like Rust, Kotlin also supports a more compact single-expression function syntax (fun double(n: Int) = n * 2, with no braces or return needed), but writing it out with return and braces, as below, is clearer while you're getting comfortable with functions.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10