[英]Can I use java lambda expression in kotlin?
I come from java, I am used to java lambdas, now I am working in a kotlin project and I see that there are other kind of lambdas, since I prefer java syntax (I also read they are better in performance)我来自 java,我习惯了 java lambda,现在我在一个 kotlin 项目中工作,我看到还有其他类型的 lambda,因为我更喜欢 java 语法(我还读到它们的性能更好)
Can I still use java lambdas in kotlin?
我还能在 kotlin 中使用 java lambdas 吗?
I try to do it but it doesn´t compile:我尝试这样做,但它没有编译:
Syntactically, no.从语法上讲,没有。 In Kotlin, you can only write lambdas in the Kotlin way, ie
在 Kotlin 中,只能用 Kotlin 的方式编写 lambda,即
{ p1, p2, p3 -> ... }
That doesn't mean that you can't pass Kotlin lambdas to Java APIs accepting a functional interface though.这并不意味着您不能将 Kotlin lambda 传递给接受函数式接口的 Java API。 This is totally possible.
这是完全可能的。
After all, Kotlin and Java are two different languages and have different syntaxes.毕竟,Kotlin 和 Java 是两种不同的语言,有不同的语法。
// Stream.map is a Java API, but it can take a "Kotlin lambda" just fine
ids.stream().map { anId -> anId + 1 }
However, since you mention that Java lambdas are "better in performance" (assuming you mean that they are compiled to invokedynamic
calls), it should be noted that Kotlin lambdas do this too since Kotlin 1.5, under certain circumstances, as discussed here :但是,由于您提到 Java lambdas “性能更好”(假设您的意思是它们被编译为调用动态调用),因此应该注意
invokedynamic
lambdas 在某些情况下自 Kotlin 1.5 起也这样做,如此处所述:
Kotlin 1.5.0 now uses dynamic invocations (
invokedynamic
) for compiling SAM (Single Abstract Method) conversions:Kotlin 1.5.0 现在使用动态调用 (
invokedynamic
) 来编译 SAM(单一抽象方法)转换:
- Over any expression if the SAM type is a Java interface
如果 SAM 类型是 Java 接口,则在任何表达式上
- Over lambda if the SAM type is a Kotlin functional interface
如果 SAM 类型是 Kotlin 函数式接口,则超过 lambda
So the Stream.map
call above would be compiled using invokedynamic
, just like a Java lambda would, because it is a conversion to the Java interface java.util.function.Function
.所以上面的
Stream.map
调用将使用invokedynamic
编译,就像 Java lambda 一样,因为它是对 Java 接口java.util.function.Function
的转换。 On the other hand, a regular Kotlin lambda would be compiled to an anonymous inner class.另一方面,常规的 Kotlin lambda 将被编译为匿名内部类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.