BeginnerLesson 5 of 16
Functions – Kotlin
Default values, named arguments, vararg, and returning multiple values.
Functions begin with fun. The return type comes after the colon. If the body consists of a single expression, you write it after = – the type is then inferred.
fun quadrat(x: Int): Int {
return x * x
}
fun kubik(x: Int) = x * x * x // expression body
fun gruss(name: String, gruss: String = "Hello", laut: Boolean = false): String {
val text = "$gruss, $name!"
return if (laut) text.uppercase() else text
}
println(gruss("Ada")) // Hello, Ada!
println(gruss("Linus", laut = true)) // HELLO, LINUS!
println(gruss(gruss = "Hi", name = "Bob")) // Hi, Bob!Default values and named arguments replace many overloads in Kotlin. With vararg you accept any number of arguments, and with the spread operator * you pass on an array. You return multiple values as a Pair or a data class.
fun summe(vararg zahlen: Int) = zahlen.sum()
println(summe(1, 2, 3, 4)) // 10
val arr = intArrayOf(5, 6)
println(summe(*arr)) // 11
fun teileMitRest(a: Int, b: Int) = Pair(a / b, a % b)
val (quotient, rest) = teileMitRest(17, 5)
println("$quotient remainder $rest") // 3 remainder 2TipFunctions can also be declared locally inside other functions and access their variables. Functions without a meaningful return value return
Unit (equivalent to void).WarningFunction parameters are always immutable (like
val). You cannot assign a new value to a parameter.