简体   繁体   English

从Java调用Kotlin高阶函数

[英]Calling a Kotlin higher-order function from Java

I have a Kotlin helper class defined as: 我有一个Kotlin助手类定义为:

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. RemainingTime是一个数据类,包含到结束日期之前的时间量(秒,分钟,小时等)。

I can use this class from Kotlin cleanly: 我可以干净利用Kotlin的这个课程:

        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): 但是当我从Java调用它时,我被迫在回调中提供一个不必要的返回值,即使匿名函数指定了Unit返回类型(理论上它相当于Java void返回类型):

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

While not technically a problem, having to do provide a meaningless return value from the Java callback seems .. wrong. 虽然从技术上讲不是问题,但是从Java回调中提供无意义的返回值似乎是错误的。 Is there a better way to express this callback in Kotlin? 有没有更好的方式在Kotlin中表达这种回调?

Unit is an object and is not directly equivalent to void . Unit是一个object ,并不直接等同于void In the background even the kotlin code will include return Unit.INSTANCE; 在后台甚至kotlin代码将包括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 . 除了定义一个总是返回void的单独接口之外,没有办法解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM