I have a Kotlin helper class defined as:

class CountdownTimer(endDateInSeconds: Long, callback: (timeRemaining: RemainingTime) -> Unit)

which as the name implies, takes an epoch time and a callback to be invoked at fixed intervals (seconds in this case) until the end date is reached. RemainingTime is a data class containing the amount of time (seconds, mins, hours etc) until the end date.

I can use this class from Kotlin cleanly:

        countdownTimer = CountdownTimer(endDate, { timeRemaining ->
             var timeString = // format time remaining into a string
             view?.updateCountdownTimer(timeString)
         })

However when I call this from Java, I am forced to provide an unnecessary return value in the callback, even though the anonymous function specifies a Unit return type (which in theory is the equivalent of a Java void return type):

        this.countdownTimer = new CountdownTimer(this.endDate, remainingTime -> {
             var timeString = // format time remaining into a string
             if (view != null) {
                 view.updateCountdownTimer(timeString);
             }
             return null;
        });

虽然从技术上讲这不是一个问题,但不得不从Java回调中提供一个毫无意义的返回值似乎..错误的在Kotlin中有没有更好的方式来表达这个回调?

推荐答案

Unit is an object and is not directly equivalent to void. In the background even the kotlin code will include return Unit.INSTANCE; at the end of the callback. There is no way around that except for defining a separate interface that always returns void.

Kotlin相关问答推荐

Kotlin—从列表中枚举属性计算不同值的数量

Jetpack Compose Material3和Material2 Slider onValueChangeFinded()的行为不同

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

如何定义一个函数来接受任何具有特定字段的数据类

collectAsState 未从存储库接收更改

如何使用 Kotlin Maven 更改 Minecraft 插件中的 Shulker GUI 标题

Webpack 配置未应用于 kotlin 多平台react 项目

为什么会出现Kotlin.Unit错误以及如何修复它?

使用 Jetpack Compose 使用参数导航

如何在 micronaut 上启用 swagger UI?

如何使用函数类型或 lambdas 作为 Kotlin 上下文接收器的类型?

如果不为空,则为 builder 设置一个值 - Kotlin

kotlin 如何决定 lambda 中的参数名称?

将 Kotlin 类属性设置器作为函数引用

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

如何从kotlin中的类实例化对象

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

Kotlin 中更好的回调方法是什么?侦听器与高阶函数

将字符串编码为Kotlin中的UTF-8