Kotlin Functions
Declare typed parameters and a return type.
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
Explanation
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.
Explore the dry run
Guided walkthroughReady
1
fun average(values: List<Int>): Double {2
return values.sum().toDouble() / values.size3
}4
5
fun 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
| Step / line | What happens | State after step | Output 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 |
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.