解释这个Kotlin函数结构

Vla*_*lov 2 android function explain kotlin

我正在使用这个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
})
Run Code Online (Sandbox Code Playgroud)

zsm*_*b13 6

您的示例中使用的功能是SAM构造函数.该setOnEditorActionListener监听器需要一个OnEditorActionListener作为参数.此接口只有一个必须实现的方法,这使其成为单一抽象方法(SAM)接口.

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

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

一对一转换到Kotlin会给你:

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

但是,Kotlin允许您通过传入lambda来使用以SAM接口作为参数的方法,并使用更简洁的语法.这称为SAM转换:

mPasswordView.setOnEditorActionListener { v, actionId, event ->
    attemptLogin()
    true
}
Run Code Online (Sandbox Code Playgroud)

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

mPasswordView.setOnEditorActionListener( TextView.OnEditorActionListener { v, actionId, event ->
    attemptLogin()
    true
})
Run Code Online (Sandbox Code Playgroud)

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

有关SAM转换的官方文档