Kotlin 循环

作者: GexYY | 来源:发表于2018-06-01 11:17 被阅读0次

    For循环

    //遍历数据
     val items = listOf("aaa", "bbb", "ccc")
     for (item in items) {
            println(item)
      }
    输出结果 aaa,bbb,ccc
    
    //包含最后一位边界
     for (i in 1..5) {
        print("$i ")
      }
    输出结果 1,2,3,4,5
    
    //不包含最后一位边界
    for (i in 1 until 5) {
        print("$i ")
      }
    输出结果 1,2,3,4
    
    //每隔n个值输出获取
     for (i in 1..10 step 2) {
        print("$i ")
      }
    输出结果 1,3,5,7,9
    
    for (i in 10 downTo 6) {
        print("$i ")
      }
    输出结果: 10,9,8,7,6
    
    gex@ for (i in 1..10 step 2) {
                LogUtils.e("gex", "gex ->: $i")
                km@ for (j in 1..4) {
                    LogUtils.e("gex", "km ->: $j")
                    when {
                        j == 2 -> {
                            continue@km
                        }
                        i == 3 -> {
                            break@gex
                        }
                    }
                }
            }
    输出结果:
       gex ->: 1
        km ->: 1
        km ->: 2
        km ->: 3
        km ->: 4
        gex ->: 3
        km ->: 1
    

    ForEach 循环

    正常return,会直接用在整个方法上,forEach中return之后,以后的代码都不会执行,如下:

    fun test() {
     var ins = arrayOf(1, 2, 3, 4)
            ins.forEach {
                if (it == 2) return
                LogUtils.e("gex", "gex -> : $it")
            }
    
            ins.forEach(fun(i: Int) {
                if (i == 2) return
                LogUtils.e("gex", "km -> : $i")
            })
    }
    输出结果: gex -> : 1
    

    return @tag标签 ,相当于跳过continue的作用,如下:

    
    fun test() {
            var ins = arrayOf(1, 2, 3, 4)
            ins.forEach {
                if (it == 2) return@forEach
                LogUtils.e("gex", "gex -> : $it")
            }
            // forEach()传入方法体,然后方法体中return,效果类似于上边的retuan@Each的效果,都是等同于continue跳过的作用
            ins.forEach(fun(i: Int) {
                if (i == 2) return
                LogUtils.e("gex", "km -> : $i")
            })
        }
    输出结果:
        gex -> : 1
        gex -> : 3
        gex -> : 4
        km -> : 1
        km -> : 3
        km -> : 4
    
    //forEach传入方法break方法
    fun test() {
            var ins = arrayOf(1, 2, 3, 4)
            ins.forEach {
                if (it == 2) return@forEach
                LogUtils.e("gex", "gex -> : $it")
            }
    
            run out@{
                ins.forEach (fun(i: Int) {
                    if(i==2)return@out
                    LogUtils.e("gex", "km -> : $i")
                })
            }
        }
    输出结果:
        gex -> : 1
        gex -> : 3
        gex -> : 4
        km -> : 1
    

    相关文章

      网友评论

        本文标题:Kotlin 循环

        本文链接:https://www.haomeiwen.com/subject/zsbhsftx.html