Lesson 3 of 8
Functions, when & Expressions
Learn how to write , use default and named , and branch with if and when. In Kotlin both if and when return values, which keeps many functions short.
// Full form:
fun add(a: Int, b: Int): Int {
return a + b
}
// Expression body — same thing:
fun add2(a: Int, b: Int) = a + b
// Default and named arguments:
fun greet(name: String, greeting: String = "Hello") =
"$greeting, $name!"
fun main() {
println(greet("Ada")) // Hello, Ada!
println(greet("Ada", greeting = "Hey")) // Hey, Ada!
// if is an expression:
val grade = 87
val letter = if (grade >= 90) "A" else if (grade >= 80) "B" else "C"
println(letter)
}fun describe(x: Any): String = when (x) {
0 -> "zero"
1, 2, 3 -> "small"
in 4..99 -> "medium" // ranges
is String -> "a string of length ${x.length}" // smart cast
else -> "something else"
}
fun main() {
// Loops:
for (i in 1..5) print(i) // 12345 (inclusive)
for (i in 5 downTo 1) print(i) // 54321
for (i in 0 until 10 step 2) print(i) // 02468
val fruits = listOf("apple", "banana")
for (fruit in fruits) println(fruit)
for ((index, fruit) in fruits.withIndex()) println("$index: $fruit")
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.