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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With