1. forEach
kotlin 中可以使用 forEach遍历数组
fun testFor() {
// 声明一个数组
val array = Array(10) { num -> num }
array.forEach {
Log.e("test", "it:$it")
}
}
forEach 中不能使用break,continue关键字,如果需要跳出循环可以使用标签 loop@
fun testFor() {
// 声明一个数组
val array = Array(10) { num -> num }
array.forEach loop@{
array.forEach {
if (it == 3) {
return@loop
}
Log.e("test", "it:$it")
}
}
}
标签就是加了一个指令入口,执行 return@loop 就会跳到指定的位置,这样就可以实现跳出循环了,上面的代码相当于 执行了 for 循环的 break 关键字,如果放在第二个 forEach 后面就相当于执行了 java 中的 continue 关键字
2. for 循环
简单的 for 循环和 java 类似
/**
* for循环测试
*/
fun testFor() {
// 声明一个数组
val array = Array(10) { num -> num }
for (i in array) {
Log.e("test", "i:$i")
}
}
for 循环中 return, break, continue和 Java 中的作用一样
fun testFor() {
// 声明一个数组
val array = Array(10) { num -> num }
for (i in array) {
Log.e("test", "i:$i")
for (j in array) {
if (j == 5) {
//return // 退出方法
//break // 退出当前循环
continue // 退出这次循环,进行下一次循环
}
Log.e("test", "j:$j")
}
}
}
也可以在 for 循环中添加标签
fun testFor() {
// 声明一个数组
val array = Array(10) { num -> num }
// 标签 loop@
loop@ for (i in array) {
Log.e("test", "i:$i")
for (j in array) {
if (j == 5) {
//continue@loop // 相当于执行了 brake
break@loop // 相当于执行了 return
}
Log.e("test", "j:$j")
}
}
}
kotlin 中的 for 还有其他的一些用法
fun testFor() {
// 声明一个数组
val array = arrayOf("a", "b", "c", "d", "e", "f", "g")
// 遍历索引
for (i in array.indices) {
Log.e("test", "i:$i")
}
// 遍历索引
for (i in 0..array.lastIndex) {
Log.e("test", "i:$i")
}
// 遍历索引和值
for ((index, value) in array.withIndex()) {
Log.e("test", "index:$index value:$value")
}
}
3. while() 和 do while()
fun testFor() {
var i = 0
while (i < 10) {
Log.e("test", "第$i 个元素")
i++
}
}
fun testFor() {
var i = 0
// 至少执行一次
do {
Log.e("test", "第$i 个元素")
i++
} while (false)
}
kotlin 中的 while 和 do while 和 java 中的类似,没什么区别
4. when
kotlin 中没有 switch 方法,使用 when 代替,但是 when 比 switch 要强大不少
fun testFor() {
val i = 0
when (i) {
// 单个条件判断
1 -> {
}
// 多个条件判断
2, 3, 4 -> {
}
// range 判断
in 5..7 -> {
}
!in 8..10 -> {
}
else -> {
}
}
}
网友评论