when function kotlin code example

Example 1: kotlin function

fun sum(a: Int, b: Int): Int {
 return a + b
}

Example 2: Kotlin when

val x = 3
when(x) {
    3 -> println("yes")
    8 -> println("no")
    else -> println("maybe")
}
// when can also be used as an expression!
val y = when(x) {
    3 -> "yes"
    8 -> "no"
    else -> "maybe"
}
println(y) // "yes"

Example 3: function kotlin

// Declare a function in Kotlin
fun happyBirthday(name: String, age: Int): String {
    return "Happy ${age}th birthday, $name!"
}
// Call function
val greeting = happyBirthday("Anne", 32)

Tags:

Misc Example