赞
踩
fun main() {
// 1-10的闭区间
1..10
// 1-10的开区间
1 until 10
// 10-1的倒序区间
10 downTo 1
// 步长为2的区间
1..10 step 2
}
kotlin在1.8.2以上就推荐倒序的写法为:
1 ..< 10 //原来 1 until 10
- 1
遍历方法有很多,如for…in 、toList 等。
可以使用forEach进行遍历:
fun main() {
( 1..10 step 2).forEach(){
println(it)
}
}
但是,forEach方法不能进行遍历浮点型。
使用toList()进行遍历:
fun main() {
( 1..<10).toList().forEachIndexed({ i, v -> println("$i: $v") })
}
fun main() {
println(1.1F in 1f..<10f)
}
返回一个boolean的类型。
遍历变量c,范围从a到z:
fun main() {
for (c in 'a'..'z') println(c)
}
fun main() {
//步长为2
for (c in 'a'..'z' step 2) println(c)
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。