Step 3 of 13
if and when expressions, loops, functions with default and named arguments, vararg
if/when expressions, loops, และฟังก์ชัน — รวมถึง default arguments, named arguments, vararg
In Kotlin, if is an expression — it returns a value:
val score = 85
val grade = if (score >= 80) {
"A"
} else if (score >= 70) {
"B"
} else {
"C"
}
println(grade) // A
You can also write it on one line for simple cases:
val status = if (age >= 18) "Adult" else "Minor"
when is Kotlin's version of switch. It is more powerful:
val day = 3
val name = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
else -> "Weekend"
}
println(name) // Wednesday
You can match multiple values, ranges, and conditions:
val score = 75
val result = when {
score >= 90 -> "Excellent"
score in 70..89 -> "Good"
score in 50..69 -> "Pass"
else -> "Fail"
}
println(result) // Good
// for loop with range
for (i in 1..5) {
print("$i ") // 1 2 3 4 5
}
// for loop with step
for (i in 1..10 step 2) {
print("$i ") // 1 3 5 7 9
}
// for loop with list
val fruits = listOf("apple", "banana", "cherry")
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}
// 0: apple
// 1: banana
// 2: cherry
// while loop
var count = 3
while (count > 0) {
println("Count: $count")
count--
}
fun greet(name: String): String {
return "Hello, $name!"
}
println(greet("Alice")) // Hello, Alice!
Short functions can skip the braces and return:
fun add(a: Int, b: Int): Int = a + b
println(add(3, 4)) // 7
fun greet(name: String, greeting: String = "Hello"): String {
return "$greeting, $name!"
}
println(greet("Bob")) // Hello, Bob!
println(greet("Bob", "Hi")) // Hi, Bob!
When a function has many parameters, use names for clarity:
fun createUser(name: String, age: Int, active: Boolean, admin: Boolean) {
// ...
}
createUser(
name = "Alice",
age = 30,
active = true,
admin = false
)
fun sum(vararg numbers: Int): Int {
return numbers.sum()
}
println(sum(1, 2, 3)) // 6
println(sum(10, 20, 30, 40)) // 100
Write a function that classifies a number:
fun classify(n: Int): String = when {
n > 0 -> "Positive"
n < 0 -> "Negative"
else -> "Zero"
}
fun main() {
println(classify(5)) // Positive
println(classify(-3)) // Negative
println(classify(0)) // Zero
}
Try modifying classify to also handle ranges like "Small positive" (1-9) and "Large positive" (10+).