Calling Java Functional Interfaces from Kotlin
A brief demonstration of how to call functional interfaces from Kotlin using both single- and multi-use generics.
Join the DZone community and get the full member experience.Join For Free
Below is a Functional Interface defined in Java:
Note, that an interface does not need to be annotated with
@FunctionalInterfaceto be treated as one.
In Kotlin, this can be implemented with the following code:
Executor interface has only a single function, with a single input parameter, it can assign a type to the lambda passed to
execute. This removes the need to define it explicitly as
Runnable. This is known as SAM (Single Abstract Method) conversion, see the Kotlin docs for more information.
A more verbose way to achieve the same goal looks like:
If you are using Intellij, it will kindly guide you to the first solution.
Let’s make it a bit more exciting and include some generics this time round. Taking the Java interface and a function to call it:
doStuff function can be called with the following Kotlin code:
The return type of the most simplified code is determined by the lambda’s result, which in this case is a
What about when the generics get a bit more complicated? I have spiced up the example code a bit to demonstrate this:
I actually had a bit of trouble thinking of an example to demonstrate both input and output generics. I believe this code is pretty ugly and is unlikely to represent genuine code. Still, it should be good enough for an example.
To call this you would use the code below:
As I mentioned a second ago, realistically, the generic input types
B in this example would be provided from an external source. Furthermore, the generic types would be specified on an overarching class or be locked down to specific types from the beginning.
If you enjoyed this post or found it helpful (or both) then please feel free to follow me on Twitter at @LankyDanDev and remember to share with anyone else who might find this useful!
Published at DZone with permission of Dan Newton, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.