kotlin(六):基本语法之返回跳转

2018-09-06  本文已影响0人  小川君

kotlin与其他语言一样同样有三种跳出结构的方式

return 默认情况下,从最近的一个封闭的方法或者表达式跳出
break 跳出最近的封闭循环
continue 跳出本次循环 进入下次循环

kotlin中任何表达式都可以用lable{:.keyword}标签来标记,label的格式是被@标识符标记
如果有多重循环,带标签的break会跳转出标签所指示的那一个循环.带continue会调转到标签所指向的那个循环,进入该循环的下一次循环(常用语嵌套循环中)

fun test(){
    l@ for (index in 1..10){
            println("chuan: index $index")
        for(j in 1..10){
             println("chuan: j  $j")
            if(index == 4){
                continue@l
            }
            if(index == 5 && j == 3){
                breadk@l
            }
        
    }
    println("chuan----循环完毕----")
}
    
kotlinTest.test()

先来介绍下test函数这个结构体,总的是一个for循环,里面还嵌套有一个for循环,都是从一到十循环,内外层每次循环都会打印一次,主要是内层循环里面的判断,我们来看下
当外层循环等于4时,会终止当前循环,后面跟有一个@l标识,与外层循环开头命名的l@相对应,总的意思就是会跳出当前循环,并进行下一次的循环,但是跳出的不是内部循环,而是外部循环,可以参考下打印的日志,在外部循环打印了 chuan:index 4 以及内部循环打印了chuan:j 1之后,因为触发了判断条件,所以直接跳出了外部循环的本次循环,直接开始了外部循环的第五次循环,也就是日志所打印的chuan: index 5
再来看第二个判断,如果外部循环等于5,并且内部循环等于3的时候,直接break了,后面依然跟着@l,我们来看下日志,发现中断了外部循环,也就是中断了所有的循环,直接打印了 chaun----循环完毕----

完整输出如下:
2064-2064/com.chuan.jun I/System.out: chuan: index 1
    chuan: j  1
    chuan: j  2
    chuan: j  3
    chuan: j  4
    chuan: j  5
    chuan: j  6
    chuan: j  7
    chuan: j  8
    chuan: j  9
    chuan: j  10
    chuan: index 2
2064-2064/com.chuan.jun I/System.out: chuan: j  1
    chuan: j  2
    chuan: j  3
    chuan: j  4
    chuan: j  5
    chuan: j  6
    chuan: j  7
    chuan: j  8
    chuan: j  9
    chuan: j  10
    chuan: index 3
    chuan: j  1
2064-2064/com.chuan.jun I/System.out: chuan: j  2
    chuan: j  3
    chuan: j  4
    chuan: j  5
    chuan: j  6
    chuan: j  7
    chuan: j  8
    chuan: j  9
    chuan: j  10
    chuan: index 4
    chuan: j  1
    chuan: index 5
    chuan: j  1
    chuan: j  2
    chuan: j  3
    chuan----循环完毕----

关于返回语句return 没有什么太大的改动,但是kotlin中引入了内部函数,因此return如果在内部函数中使用的话,则会跳出内部函数,外部函数还是会继续的调用

  fun test(){
        println("进入test方法 ")
        fun returnMethod(age: Int){
            println("进入到returnMethod方法  $age")
            when(age){
                1 -> return
                else -> println("进入else")
            }
        }
        returnMethod(1)
        println("完毕")
    }
    
    
2919-2919/com.chuan.jun I/System.out: 进入test方法 
2919-2919/com.chuan.jun I/System.out: 进入到returnMethod方法  1
完毕
上一篇 下一篇

猜你喜欢

热点阅读