Kotlin 范围
Range 是 Kotlin 相对 Java 新增的一种表达式,它表示的是值的范围,类似于数学中的区间。
Kotlin 范围
使用 for 循环,还可以使用 .. 创建值的范围:
实例
打印整个字母表:
fun main() {for (chars in 'a'..'x') {println(chars)}}
您还可以创建数字范围:
实例
fun main() {for (nums in 5..15) {println(nums)}}
备注:第一个和最后一个值包含在范围内。
检查值是否存在
你可以使用 in 运算符来检查一个值是否存在于某个区间范围内:
实例
fun main() {val nums = arrayOf(2, 4, 6, 8)if (2 in nums) {println("It exists!")} else {println("It does not exist.")}}
实例
fun main() {val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")if ("Volvo" in cars) {println("It exists!")} else {println("It does not exist.")}}
终止或继续一个区间范围
您还可以在 区间范围/for 循环中使用 break 和 continue 关键字:
实例
当 nums 等于 10 时停止循环:
fun main() {for (nums in 5..15) {if (nums == 10) {break}println(nums)}}
实例
跳过循环中的值 10,继续下一次迭代:
fun main() {for (nums in 5..15) {if (nums == 10) {continue}println(nums)}}