Kotlin Ranges
Kotlin 范围
With the for
loop, you can also create ranges of values with "..
":
You can also create ranges of numbers:
Note: The first and last value is included in the range.
Check if a Value Exists
You can also use the in
operator to check if a value exists in a range:
例子
val nums = arrayOf(2, 4, 6, 8)
if (2 in nums) {
println("It exists!")
} else {
println("It does not exist.")
}
亲自尝试 »
例子
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
println("It exists!")
} else {
println("It does not exist.")
}
亲自尝试 »
Break or Continue a Range
You can also use the break
and continue
keywords in a range/for
loop:
例子
Stop the loop when nums
is equal to 10
:
for (nums in 5..15) {
if (nums == 10) {
break
}
println(nums)
}
亲自尝试 »
例子
Skip the value of 10 in the loop, and continue with the next iteration:
for (nums in 5..15) {
if (nums == 10) {
continue
}
println(nums)
}
亲自尝试 »