您的示例中使用的功能是SAM构造函数 https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions. The 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 允许您通过传入 lambda 来使用以 SAM 接口作为参数的方法,语法更简洁。这称为 SAM 转换:
mPasswordView.setOnEditorActionListener { v, actionId, event ->
attemptLogin()
true
}
SAM 转换自动确定该 lambda 对应于哪个接口,但您可以使用称为 SAM 构造函数的东西显式指定它,这就是示例代码中的内容。 SAM 构造函数返回一个实现给定接口的对象,并使您传递给它的 lambda 成为其单个方法的实现。
mPasswordView.setOnEditorActionListener( TextView.OnEditorActionListener { v, actionId, event ->
attemptLogin()
true
})
在这种特定情况下这是多余的,因为只有一种方法称为setOnEditorActionListener
。但是,如果有多个具有相同名称的方法,并且采用不同的接口作为参数,则可以使用 SAM 构造函数来指定要调用的方法的哪个重载。
有关 SAM 转换的官方文档 https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions