简体   繁体   中英

what is the equivalent of this kotlin code to java

The following is some kotlin code that prints the execution time of any statement or block of statements:

fun exeTime(code: () -> Unit) {
    var start = System.currentTimeMillis()
    code()
    var end = System.currentTimeMillis() - start
    println("Execution time: " + end + "ms")
}

It can be used like this:

exeTime {
    // some code
    // ...
}

What is the equivalent construct in Java for the exeTime function?

I will be something like:

public void exeTime(Runnable code){
    long start = System.currentTimeMillis();
    code.run();
    long end = System.currentTimeMillis() - start;
    System.out.println("Execution time: " + end + "ms");
}

Read this doc about higher-order functions and lambdas

Well, Java has no data type as Unit, so basically you can't pass a method instead of it's value. When you pass a method as an argument of a method in Java, it executes. If you need to do the same in Java easiest way to use reflection. Something similar to this.

void <T> execTime (Class<T> type, String methodName, Object... methodParams) {

}

That's an easy example of a "higher order function", ie a function that takes another function as an argument. In Java you can also use lambdas as of 1.8 which could look as follows:

public static void main(String[] args) {
    exeTime(v -> System.out.println("from Lambda"));
}

static void exeTime(Consumer<Void> code) {
    long start = System.currentTimeMillis();
    code.accept(null);
    long end = System.currentTimeMillis() - start;
    System.out.println("Execution time: " + end + "ms");
}

Also Runnable could be used as the interface type.

Before 1.8 you would have used an anonymous function instead of the lambda passed to the exeTime function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM