Calling Scala from Java

Jaideep Ganguly

I think attempting Scala from java is slightly skewed philosophically. Because both of them differ on paradigms. On top of my head, here are a few differences:

JavaScala
Three namespaces: packages, methods, fieldsUniform access principle
Has primitivesSingle Object model. Everything is an object
Special (irregular) handling of arraysArrays are just like any other collection
void, nullUnit, Nothing
......

JVM does not have bytecode support for a lot of stuff scala tries. So scala has to resort to many hacks to make those paradigms a reality.

A small example:

So x is supposed to be final. Well in bytecode it is not. Below is a working java code

x is technically useless. Means its visibility is only intrait J. But here in bytecode we can see that is public and can be accessed.

Now look at this:

So it is here at 5, it calls J$class.class which calls InterfaceMethod J.J\$_setter_\$J\$\$x_\$eq:(Ljava/lang/String;) V

Technically the compiler is fooling us. What it portrays is far from what it actually is in reality. All thus due to lack of bytecode support.

Another example:

Now line-acompiles successfully. But it throws an error at runtime. Why? Because at bycode level, func expects a String[].

At line-(a) we pass Object[]. But why Object[]? Because in scala, Nothing is subtype of every other type. But how do we express this at byte code. We cant >.<. Hence Object[] is used.

Note this issue is only with arrays as they are reified. Works alright with List as it is type-erased.

Bottom-Line: It is futile to attempt calling scala from java. Scala has a rich type system which cannot be directly expressed from Java. Solution: Hava a java wrapper for your scala code.