简体   繁体   English

这个 kotlin 代码与 java 的等价物是什么

[英]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:以下是一些打印任何语句或语句块的执行时间的kotlin代码:

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? Java 中exeTime函数的等效构造是什么?

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阅读有关高阶函数和 lambda 的文档

Well, Java has no data type as Unit, so basically you can't pass a method instead of it's value.好吧,Java 没有作为 Unit 的数据类型,所以基本上你不能传递一个方法而不是它的值。 When you pass a method as an argument of a method in Java, it executes.当您将方法作为 Java 方法的参数传递时,它会执行。 If you need to do the same in Java easiest way to use reflection.如果你需要在 Java 中做同样的事情,使用反射的最简单方法。 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:在 Java 中,您还可以使用 1.8 版的 lambda 表达式,如下所示:

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. Runnable也可以用作接口类型。

Before 1.8 you would have used an anonymous function instead of the lambda passed to the exeTime function.在 1.8 之前,您将使用匿名函数而不是传递给exeTime函数的 lambda。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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