【问题标题】:Explain this Kotlin function structure解释一下这个 Kotlin 函数结构
【发布时间】:2017-09-20 07:31:25
【问题描述】:

我正在使用这个 Kotlin 函数。我知道我们有一个名为mPasswordView!!.setOnEditorActionListener 的函数,它接受参数TextView.OnEditorActionListener,但它后面是什么?我们在参数中有大括号?

mPasswordView!!.setOnEditorActionListener(TextView.OnEditorActionListener { textView, id, keyEvent ->
    if (id == R.id.login || id == EditorInfo.IME_NULL) {
        attemptLogin()
        return@OnEditorActionListener true
    }
    false
})

【问题讨论】:

  • 好吧,我的错。这不是一个函数...

标签: android function kotlin explain


【解决方案1】:

您的示例中使用的功能是SAM constructor。 setOnEditorActionListener 侦听器将 OnEditorActionListener 作为其参数。此接口只有一个您必须实现的方法,这使其成为单一抽象方法 (SAM) 接口。

在 Java 中使用此方法的完整语法是:

mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        attemptLogin();
        return true;
    }
});

到 Kotlin 的一对一转换将为您提供:

mPasswordView.setOnEditorActionListener(object: TextView.OnEditorActionListener{
    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        attemptLogin()
        return true
    }
})

然而,Kotlin 允许您使用以 SAM 接口作为参数的方法,其语法更简洁,而是传入一个 lambda。这称为 SAM 转换:

mPasswordView.setOnEditorActionListener { v, actionId, event ->
    attemptLogin()
    true
}

SAM 转换会自动确定此 lambda 对应于哪个接口,但您可以使用称为 SAM 构造函数的东西显式指定它,这就是您的示例代码中的内容。 SAM 构造函数返回一个实现给定接口的对象,并使您传递给它的 lambda 成为其单一方法的实现。

mPasswordView.setOnEditorActionListener( TextView.OnEditorActionListener { v, actionId, event ->
    attemptLogin()
    true
})

在这种特定情况下这是多余的,因为只有一个方法称为setOnEditorActionListener。但是,如果有多个同名的方法,将不同的接口作为参数,则可以使用 SAM 构造函数来指定要调用的方法的哪个重载。

Official docs about SAM conversions

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多