Home > Enterprise >  Can I use java lambda expression in kotlin?
Can I use java lambda expression in kotlin?

Time:05-17

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)

Can I still use java lambdas in kotlin?

I try to do it but it doesn´t compile:

enter image description here

CodePudding user response:

Syntactically, no. In Kotlin, you can only write lambdas in the Kotlin way, i.e.

{ p1, p2, p3 -> ... }

That doesn't mean that you can't pass Kotlin lambdas to Java APIs accepting a functional interface though. This is totally possible.

After all, Kotlin and Java are two different languages and have different syntaxes.

// 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:

Kotlin 1.5.0 now uses dynamic invocations (invokedynamic) for compiling SAM (Single Abstract Method) conversions:

  • Over any expression if the SAM type is a Java interface
  • Over lambda if the SAM type is a Kotlin functional interface

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. On the other hand, a regular Kotlin lambda would be compiled to an anonymous inner class.

  • Related