Kotlin
Beginner
1 min read
Destructuring and Range Expressions
Example
data class Point(val x: Int, val y: Int)
fun main() {
// Destructuring a data class
val (x, y) = Point(3, 7)
println("x=$x y=$y")
// Destructuring a map entry
val scores = mapOf("Alice" to 95, "Bob" to 87)
for ((name, score) in scores) {
println("$name scored $score")
}
// Pair and Triple
val (first, second) = Pair("Kotlin", 2011)
println("$first launched in $second")
// Closed range (inclusive on both ends)
val range = 1..10
println(5 in range) // true
println(11 in range) // false
// Half-open range
for (i in 0 until 5) print("$i ") // 0 1 2 3 4
println()
// Step and downTo
for (i in 10 downTo 1 step 2) print("$i ") // 10 8 6 4 2
println()
// Char range
for (ch in 'a'..'e') print(ch) // abcde
println()
// Range in when
val age = 20
val category = when (age) {
in 0..12 -> "Child"
in 13..17 -> "Teen"
in 18..64 -> "Adult"
else -> "Senior"
}
println(category) // Adult
}
Related Resources
Kotlin Reference
Complete tag & property list
Kotlin How-To Guides
Step-by-step practical guides
Kotlin Exercises
Practice what you've learned
More in Kotlin