Calling Scala from Java

If I call from Java a Scala method with a (Int,String) return type, the Java type I get is Tuple2<Object,String>. Is that expected? Is it safe to typecast the Object to Integer (or even to int)?

Answer in the FAQ!

BTW, note that common advice for Java-Scala interop is to define a plain Java interface as the middleware.


@SethTisue :wink:

3 Likes

Thanks. I’m running into the problem while implementing the Java middleware. So, is it safe to typecast or could the object be something other than Integer in some cases?

AFAIK yes, it should just be an Integer.

while implementing the Java middleware

Why?
The idea of having such interface in the middle is precisely to avoid calling any Scala code directly from Java. The idea is that Java code always calls Java code thought a Java interface which is then implemented by some Scala code, so you should never be on a situation like:

If I call from Java a Scala method with a (Int,String) return type, the Java type I get is Tuple2<Object,String> .

I had some classes implemented in Java in an effort to hide Scala as much as possible (I want some return types from my Java interface to be classes, not interfaces), but I’ve started to write them in Scala instead. This means that Java users will be using Scala classes directly, but those will be very Java-like classes, with no Scala features visible.