ranges的使用 (1)使用in操作符检查一个数是否在某个范围内 [plain] view plain copy print ? /* 判断分数是否大于等于90,小于等于100 */ fun isGood(score: Int) { if(score in 90..100) //ranges是闭区间 println("very good") else println("not so good") } (2)检查索引是否越界 [plain] view plain copy print ? /* 检查index是否在数组arr的索引范围内 */ fun checkIndex(index: Int, arr: Array<Int>) { if(index in 0..arr.lastIndex) //arr.lastIndex返回的是数组的最后一位的下标 println("index in bounds") else println("index out of bounds") } (3)遍历一个范围 [plain] view plain copy print ? for(i in 1..5) { println(i) } 也可以通过in运算符遍历一个集合,如下代码: [plain] view plain copy print ? //in运算符遍历一个字符串数组 fun testStr(arr: Array<String>) { for(str in arr) println(str) }