最适合网络开发者的网站
Kotlin。W3Schools 英文版。初学者课程

尿素 西斯

Kotlin Ranges


Kotlin 范围

With the for loop, you can also create ranges of values with "..":

例子

Print the whole alphabet:

for (chars in 'a'..'x') {
  println(chars)
}
亲自尝试 »

You can also create ranges of numbers:

例子

for (nums in 5..15) {
  println(nums)
} 
亲自尝试 »

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)
} 
亲自尝试 »