KotlinFunctionsBeginner

fun (Function Definition)

Defines a function in Kotlin, specifying its name, parameters with types, and an optional return type.

Review the syntaxStudy the examplesOpen the coding app
fun functionName(param1: Type1, param2: Type2): ReturnType {
    // Function body
    return result
}

// Single-expression function
fun functionName(param: Type): ReturnType = expression

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Defines a function in Kotlin, specifying its name, parameters with types, and an optional return type.

Functions are the building blocks of Kotlin programs, declared using the `fun` keyword. A function definition includes its name, a list of parameters (each with a name and a type), and an optional return type. If a function does not return any meaningful value, its return type can be omitted, and it implicitly returns `Unit` (similar to `void` in Java). For functions consisting of a single expression, a concise syntax can be used where the body is directly assigned using an equals sign (`=`), and the return type can often be inferred by the compiler. Kotlin also supports default arguments, allowing parameters to have predefined values if not explicitly provided, and named arguments, which improve readability by letting you specify parameter names when calling a function. `vararg` parameters enable a function to accept a variable number of arguments of a specified type. Functions can be defined at the top level of a file, within classes (as member functions), or locally within other functions, promoting modular and organized code. Clear and descriptive function signatures are crucial for code maintainability and understanding.

Quick reference

Syntax

fun functionName(param1: Type1, param2: Type2): ReturnType {
    // Function body
    return result
}

// Single-expression function
fun functionName(param: Type): ReturnType = expression

Inputs

Parameters

param1Type1 · The name and type of the first parameter.
param2Type2 · The name and type of the second parameter.
ReturnType (optional)Type · The type of the value returned by the function. If omitted, it's `Unit`.

See it in practice

Examples

1

Basic function definition with parameters and return type

fun add(a: Int, b: Int): Int {
    return a + b
}

val sum = add(5, 3)
println("Sum: $sum")
Output:
Sum: 8

A simple function `add` that takes two integers and returns their sum.

2

Single-expression function with inferred return type

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

val product = multiply(4, 2)
println("Product: $product")
Output:
Product: 8

A concise single-expression function where the return type (`Int`) is inferred by the compiler.

3

Function with default arguments and named arguments

fun greet(name: String, greeting: String = "Hello") {
    println("$greeting, $name!")
}

greet("Alice") // Uses default greeting
greet("Bob", "Hi") // Overrides default
greet(greeting = "Hola", name = "Charlie") // Named arguments
Output:
Hello, Alice! Hi, Bob! Hola, Charlie!

The `greet` function uses a default value for `greeting`. Calls demonstrate using the default, overriding it, and using named arguments for clarity.

Debug faster

Common Errors

1

Type Mismatch / Missing Return

Cause: Forgetting to specify a return type for a function that is not a single-expression function, or returning a value of a different type than declared.

Fix: Explicitly declare the return type for functions with block bodies. Ensure the `return` statement matches the declared type. For single-expression functions, ensure the expression's type matches the expected return type or is inferable.

fun calculate(): Int {
    println("Calculating...")
    // Missing return statement
} // Error: A 'return' expression required in a function with a block body

Runtime support

Compatibility

JVMN/AKotlin 1.0+

Source: Kotlin Documentation

Common questions

Frequently Asked Questions

Defines a function in Kotlin, specifying its name, parameters with types, and an optional return type.

param1: The name and type of the first parameter. param2: The name and type of the second parameter. ReturnType: The type of the value returned by the function. If omitted, it's `Unit`.

Type Mismatch / Missing Return: Explicitly declare the return type for functions with block bodies. Ensure the `return` statement matches the declared type. For single-expression functions, ensure the expression's type matches the expected return type or is inferable.