I have a function in kotlin
fun printExecutionTime(block: () -> Any) {
run {
val currentTimeMillis = System.currentTimeMillis()
block()
Logr.d("Execution time of " + block.javaClass.name + " -> " + System.currentTimeMillis().minus(currentTimeMillis))
}
}
In java code, I want to pass void reference function as parameter, but can't bcs of return value
PerformanceKt.printExecutionTime(this::voidFunc);
One way will be to use interface
interface Action {
fun call()
}
Is it possible to declare it in kotlin without an extra interface, so the code above will work?
Have you tried using Unit
?
fun f(voidFunc: () -> Unit) {
// <...>
}
upd: After some googling I should admit, that this solution won't work for you. There's an open issue covering the use of Java method references with Kotlin functional types.
However, there's still a workaround to use in Java (looks ugly, yes):
public Unit voidFunc() {
// <...>
return null;
}
you can using java.lang.Runnable
to avoiding introduce additional interface ,for example:
fun printExecutionTime(block: Runnable) {
run {
val currentTimeMillis = System.currentTimeMillis()
block.run()
//...
}
}
then you can using java method reference expression as below:
PerformanceKt.printExecutionTime(this::voidFunc);
void voidFunc(){...}
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