Functions in Kotlin

Functions are central in Kotlin. We’ll learn about functions with a few different examples.

import kotlin.math.plus

// Here's a function that takes two Int parameters and returns
// their sum as an Int.
fun plus(a: Int, b: Int): Int {
    // Kotlin allows for single-expression functions, where the
    // return keyword can be omitted
    return a + b
}

// When you have multiple parameters of the same type, you can
// specify the type once after the parameter list
fun plusPlus(a: Int, b: Int, c: Int): Int = a + b + c

fun main() {
    // Call a function just as you'd expect, with name(args)
    val res = plus(1, 2)
    println("1+2 = $res")

    val res2 = plusPlus(1, 2, 3)
    println("1+2+3 = $res2")
}

To run the program, save it as functions.kt and use the Kotlin compiler:

$ kotlinc functions.kt -include-runtime -d functions.jar
$ java -jar functions.jar
1+2 = 3
1+2+3 = 6

There are several other features to Kotlin functions. One is multiple return values, which we’ll look at next.