Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Kotlin higher-order function from Java

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;
        });

While not technically a problem, having to do provide a meaningless return value from the Java callback seems .. wrong. Is there a better way to express this callback in Kotlin?

like image 948
Michael Scott Avatar asked Sep 06 '17 19:09

Michael Scott


1 Answers

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.

like image 184
Kiskae Avatar answered Oct 07 '22 03:10

Kiskae