Functions, Defaults & Named Arguments
Declaring functions
fun add(a: Int, b: Int): Int {
return a + b
}
fun add2(a: Int, b: Int) = a + b // single-expression function
- Parameters always need types; the return type is inferred for single-expression functions.
- Functions that return nothing return
Unit(likevoid); you can leave it out.
Default and named arguments
fun greet(name: String, greeting: String = "Hello", punctuation: String = "!") =
"$greeting, $name$punctuation"
greet("Ana") // Hello, Ana!
greet("Ben", punctuation = "?") // Hello, Ben?
Defaults replace most of Java's method overloading, and named arguments make calls self-explanatory.
vararg
fun sum(vararg nums: Int) = nums.sum(), then call sum(1, 2, 3), or spread an array with sum(*arr).
Top-level and local functions
Functions don't need to live inside a class, and you can define functions inside functions for helpers.
Infix and operator functions
infix fun Int.times(s: String) = s.repeat(this)
3 times "Hi " // "Hi Hi Hi "
operator fun plus(…) lets your own classes use +.
Nothing and TODO()
TODO("explain why") throws an error. It's handy as a placeholder while you build, and its return type is Nothing.
Example
fun add(a: Int, b: Int) = a + b
fun greet(name: String, greeting: String = "Hello", punctuation: String = "!") =
"$greeting, $name$punctuation"
fun sum(vararg nums: Int): Int = nums.sum()
fun describeOrder(item: String, qty: Int = 1, gift: Boolean = false): String {
fun price(q: Int) = q * 250 // local helper function
val giftText = if (gift) " 🎁" else ""
return "$qty × $item = Rs ${price(qty)}$giftText"
}
infix fun Int.times(s: String) = s.repeat(this)
fun main() {
println(add(2, 3))
println(greet("Ana"))
println(greet("Ben", punctuation = "?"))
println(greet(greeting = "Namaste", name = "Cara"))
println(sum(1, 2, 3, 4))
val arr = intArrayOf(5, 5)
println(sum(*arr))
println(describeOrder("Notebook"))
println(describeOrder("Pen", qty = 3, gift = true))
println(3 times "Hi ")
}