Kotlin Tutorial · Kotlin Basics · Lesson 9 of 31
Kotlin Functions
Declare functions with fun, use default and named arguments, single-expression functions and varargs.
Declaring functions
fun name(param: Type): ReturnType { ... }. A function that returns nothing useful returns Unit (you can omit
it). A single-expression function uses = instead of a body.
fun add(a: Int, b: Int): Int {
return a + b
}
fun square(x: Int) = x * x // single-expression function
fun greet(name: String) { // returns Unit
println("Hello, $name!")
}
fun sumAll(vararg numbers: Int): Int = numbers.sum()
fun main() {
println(add(2, 3))
println(square(9))
greet("Ana")
println(sumAll(1, 2, 3, 4))
}
Output
5 81 Hello, Ana! 10
Run this on your computer — see “Get Started” for setup.
Default and named arguments
Parameters can have default values, and callers can pass arguments by name in any order. This replaces most overloads and builder classes.
fun formatPrice(amount: Double, currency: String = "EUR", decimals: Int = 2): String =
"%.${decimals}f %s".format(amount, currency)
fun main() {
println(formatPrice(9.5))
println(formatPrice(9.5, "USD"))
println(formatPrice(9.5, decimals = 0))
println(formatPrice(currency = "GBP", amount = 12.0))
}
Output
9.50 EUR 9.50 USD 10 EUR 12.00 GBP
Run this on your computer — see “Get Started” for setup.
Test yourself
What does a function return when no return type is declared and it has a block body?
NothingUnitnullAny
Show answer
Answer: Unit