Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare parameter as function without return value?

Tags:

kotlin

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?

like image 672
ar-g Avatar asked Sep 07 '25 00:09

ar-g


2 Answers

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;
}
like image 131
Alexander Romanov Avatar answered Sep 08 '25 23:09

Alexander Romanov


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(){...}
like image 33
holi-java Avatar answered Sep 08 '25 22:09

holi-java