Question: Calling a Kotlin higher-order function from Java

Question

Calling a Kotlin higher-order function from Java

Answers 1
Added at 2017-09-06 21:09
Tags
Question

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?

Answers to

Calling a Kotlin higher-order function from Java

nr: #1 dodano: 2017-09-06 21:09

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.

Source Show
◀ Wstecz