当前位置:嗨网首页>书籍在线阅读

31-@操作符

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

4.8.2 @操作符 

在Kotlin中,@操作符主要有两个作用,一是限定this的对象类型,二是作为标签使用。

class User {
    inner class State{
        fun getUser(): User{
            return this@User  //返回User
        }
        fun getState(): State{
            return this@State  //返回State
        }
    }
}

当把@操作符作为标签使用时,可以跳出双层for循环和forEach函数。例如,下面是使用@操作符跳出for循环的实例。

val listA = listOf(1, 2, 3, 4, 5, 6)
val listB = listOf(2, 3, 4, 5, 6,7,8)
loop@ for (itemA in listA) {
        var i : Int = 0
        for (itemB in listB) {
            i++
            if (itemB > 2) {
                break@loop   //当itemB>2时,跳出循环
            }
            println("itemB:$itemB")   
        }
    }

运行上面的代码,输出结果为itemB:2。

同时,@操作符作为自定义标签使用时,可以通过自定义标签跳转到指定的函数中。

fun runTag(){
    run {
        println("lambda")
    }
    var i: Int = run {
        return@run 1
    }
    println("$i")
    //匿名函数可以通过自定义标签进行跳转和返回
    i = run (outer@{
        return@outer 2
    })
    println(i)
}