So I have this Java code:

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            doSomething();
            return true;
        }
        return false;
    }
});

我设法做到了这一点(我甚至不确定这是不是正确的方式):

editText.setOnEditorActionListener() { v, actionId, event ->
      if(actionId == EditorInfo.IME_ACTION_DONE){
          doSomething()
      } else {
      }
}

But I get an error Error:(26, 8) Type mismatch: inferred type is kotlin.Unit but kotlin.Boolean was expected

那么这样的事件处理程序是如何用Kotlin 编写的呢?

推荐答案

onEditorAction返回Boolean,而你的Kotlin lambda返回Unit.将其更改为:

editText.setOnEditorActionListener { v, actionId, event ->
      if(actionId == EditorInfo.IME_ACTION_DONE){
          doSomething()
          true
      } else {
          false
      }
}

The documentation on lambda expressions and anonymous functions is a good read.

Kotlin相关问答推荐

API迁移到Spring Boot 3后,Spring Security无法工作

Regex(Kotlin)仅匹配句子末尾的句号,而忽略中间的句号,如缩写

在Kotlin项目中使用Free Fair AspectJ插件(使用Gradle)

如何使用multiset与JOOQ获取关联的记录列表?

Java/Kotlin中类似Rust般的注释编译?

Kotlin:调用 CoroutineScope.launch 与在协程内启动之间的区别

如何在 Spring Boot 3 中为内部类提供运行时提示

如何使用成员引用在 Kotlin 中创建属性的分层路径

如何处理基于枚举提前返回的 forEach 循环,Kotlin 中的一条路径除外

如何在 Kotlin 中为变量分配另一个变量的值?

Jetpack BottomNavigation - java.lang.IllegalStateException:Already attached to lifecycleOwner

禁用 Android 12 默认启动画面

Kotlin 枚举中的循环引用

Kotlin 语言是如何用 Kotlin 编写的?

如何在MVVM架构中观察RecyclerView适配器中的LiveData?

kotlin RecyclerView分页

如何暂停kotlin coroutine直到收到通知

查找是否在列表中找到具有特定属性值的元素

Kotlin扩展函数与成员函数?

inflating com.google.android.material.textfield.TextInputLayout