Kotlin setOnclickListener [英] Kotlin setOnclickListener

查看:902
本文介绍了Kotlin setOnclickListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我以前只为无效方法编写return.但是kotlin似乎不允许只返回,而是使用了return@methodname? 有人可以解释一下这是什么以及它如何增加价值吗?

Back in java I used to write only return for a void method... But kotlin doesn't seem to allow just return, instead it uses return@methodname? Can someone explain what this is and how does it add value?

 bAddLine.setOnClickListener {
            val selectedSeries = getSelectedSeries()
            if (selectedSeries.isEmpty()) {
                Toast.makeText(this, getString(R.string.toast_channel_mandatory), Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
        }

推荐答案

来自 kotlinlang 网站:

返回标签

借助函数文字,局部函数和对象表达式,可以将函数嵌套在Kotlin中.合格的返回值使我们可以从外部函数返回.最重要的用例是从lambda表达式返回.回想一下,当我们写这篇文章时:

With function literals, local functions and object expression, functions can be nested in Kotlin. Qualified returns allow us to return from an outer function. The most important use case is returning from a lambda expression. Recall that when we write this:

fun foo() {
    ints.forEach {
        if (it == 0) return  // nonlocal return from inside lambda directly to the caller of foo()
        print(it)
    }
}

return表达式从最近的封闭函数foo返回. (请注意,只有传递给内联函数的lambda表达式才支持这种非本地返回.)如果需要从lambda表达式返回,则必须对其进行标记并限定return:

The return-expression returns from the nearest enclosing function, i.e. foo. (Note that such non-local returns are supported only for lambda expressions passed to inline functions.) If we need to return from a lambda expression, we have to label it and qualify the return:

fun foo() {
    ints.forEach lit@ {
        if (it == 0) return@lit
        print(it)
    }
}

现在,它仅从lambda表达式返回.通常,使用隐式标签会更方便:这样的标签与lambda传递给的函数同名.

Now, it returns only from the lambda expression. Oftentimes it is more convenient to use implicits labels: such a label has the same name as the function to which the lambda is passed.

fun foo() {
    ints.forEach {
        if (it == 0) return@forEach
        print(it)
    }
}

这篇关于Kotlin setOnclickListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆