Scala callbacks in Kotlin

Photo by Tine Ivanič on Unsplash

Passing Scala procedures to Kotlin, and invoking them may not be as trivial as it seems.

For the past few months I’ve been working on integrating Scala and Kotlin code. In both of those JVM languages, it’s common to use higher-order functions. That is, passing a function to another function.

Sometimes, those functions may also be used as callbacks. Consider a case when you would like to invoke some Kotlin code from Scala with a resource, but release this resource from Kotlin (a borrow pattern):

Signature of this function in Scala looks pretty innocent in Kotlin terms:

So you may be tempted to specify it using the same terms in Kotlin:

But that code won’t compile. The reason becomes quite obvious from the error message. Scala’s Function0 is not Kotlin’s Function0 , nor Scala’s Unit is Kotlin’s Unit

Also, block doesn’t have invoke() method Kotlin expects.

Are we stuck? Not yet.

First, let’s fix the signature of our class:

Here we specify, that that function we expect is actually a Scala function, that receives zero arguments and returns nothing.

Next, let’s invoke it:

Since it’s a Scala function, the correct way to invoke it is using apply()

In some cases, you may be tempted to define this Scala function as optional:

That’s something you shouldn’t do. You’ll get a weird error saying:

Avoid nullable callbacks from Scala to Kotlin.

It’s possible to pass Scala callbacks to code written in Kotlin. But you should use the correct Scala functional types, and be careful with nullability.

Solutions Architect @Depop, author of “Hands-on Design Patterns with Kotlin” book and “Web Development with Kotlin” course

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store