Kotlin · Course navigation

Kotlin Functions

Declare typed parameters and a return type.

On this page
Before you start

Kotlin basics.

  • Declare typed parameters and a return type.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

A Kotlin function starts with fun, lists parameters as name: Type, and declares its return type after a colon. Types are required for parameters.

values.sum() adds the integers. Converting to Double before dividing matters, because dividing two Ints in Kotlin discards the fraction. The result 344 / 4 prints as 86.0 because the value is a Double.

Code example

Kotlin
fun average(values: List<Int>): Double {
    return values.sum().toDouble() / values.size
}

fun main() {
    println(average(listOf(82, 91, 76, 95)))
}
Output
86.0

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1fun average(values: List<Int>): Double {
2 return values.sum().toDouble() / values.size
3}
4
5fun main() {
6 println(average(listOf(82, 91, 76, 95)))
7}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Take a list of ints and promise a Double.—
—
344 as a Double divided by 4.return = 86.0
—
Print the returned Double.return = 86.0
86.0

Behind the scenes

How Kotlin processes this code

Kotlin commonly compiles to JVM bytecode, which the JVM executes.

Cost and common mistakes

O(n) time and O(1) extra space.

  • Without converting to Double, 344 / 4 would use integer division and lose any remainder.
  • average(emptyList()) would divide by zero and give NaN for Doubles; check for an empty list first.

Try it yourself

Predict average(listOf(1, 2)).

Reveal answer and reasoning

The sum is 3, and 3.0 / 2 is 1.5.

Further reading