Skip to content
AgileLogics
6 min read

Functions

Prerequisites: Lists

A function is a named, reusable block of code that performs a task. You write it once and call it whenever you need it.

Real-world analogy: a function is a recipe. You write the steps once, then just say "make pancakes" whenever you want them.

Syntax

fun name(parameter: Type): ReturnType {
    // code
    return value
}

Example

fun greet(name: String): String {
    return "Hello, $name!"
}

fun main() {
    println(greet("Ada"))
    println(greet("Linus"))
}

Expected output

Hello, Ada!
Hello, Linus!

Line by line:

  • fun greet(name: String) declares a function with one parameter, name, which must be a String. Parameters always need a type.
  • : String after the parentheses is the return type.
  • return sends the result back to the caller.

Single-expression functions

When a function just returns one expression, use = and drop the braces and return. The return type can then be inferred:

fun square(n: Int) = n * n
fun isEven(n: Int) = n % 2 == 0

fun main() {
    println(square(7))
    println(isEven(7))
}
49
false

Functions that return nothing

Leave out the return type. (Technically such functions return Unit, Kotlin's "no meaningful value" type.)

fun printBanner(text: String) {
    println("*** $text ***")
}

fun main() {
    printBanner("Sale")
}
*** Sale ***

Functions can be declared before or after main in the file — order doesn't matter.

Common mistakes

  • Leaving out a parameter's type: fun greet(name) doesn't compile.
  • Declaring a return type with a block body and forgetting return: Missing return statement.

Practice

Write area(width, height) returning the area of a rectangle as a Double, and isSquare(width, height) returning a Boolean. Print both for a 4 by 4 rectangle.

Show solution
fun area(width: Double, height: Double) = width * height

fun isSquare(width: Double, height: Double) = width == height

fun main() {
    println(area(4.0, 4.0))
    println(isSquare(4.0, 4.0))
}
16.0
true