Monday, 30 November 2009

Calling Scala Object Fields from Java

It's pretty easy to call anything in Java from Scala but sometimes it can be hard to go the other way round.

I work on a large codebase that contains both Java and Scala. All new development is done in Scala but sometimes we need to update a Java class by calling some Scala code. In most cases this is easy but sometimes I run into problems.

Say you have a Scala object like so:

object JavaCallingScalaTest {
val Constant = "Constant"
}
and you want to use the 'Constant' field in a Java file. You would do this like so:

public class JavaCallingScalaTestJavaFile {
private static final String CONSTANT = JavaCallingScalaTest$.MODULE$.Constant();
}
Now lets say the Scala field is a map like so:

object JavaCallingScalaTest {
val IntToString = Map(1 -> "one", 2 -> "two")
}
and you want to extract some information out of the map in Java, you would do something like this:

public class JavaCallingScalaTestJavaFile {
private static final String TEXT_FOR_TWO = JavaCallingScalaTest$.MODULE$.IntToString().apply(2);
}
Enjoy.

No comments:

Post a Comment