Be sure to check out Groovymag for more information on Groovy, Grails, Griffon and other GR8 technologies (Gant, Gradle, Gmaven, Spock, etc...

This article has been translated to Japanese by Kazuchika Sekiya, domo arigato!
Groovy & Scala: a tale of two JVM languages
Andres AlmirayShould you choose Groovy over Scala (or vice versa) for your next project? Why not use both instead! This article will demonstrate how Groovy and Scala can talk to each other without compromising their conventions or idiomatic forms.
Introduction
The Java Virtual Machine is a big ecosystem that harbors a multitude of languages, each one with its own style (object oriented, procedural, functional, etc) and its own motivation (concurrency first, UI specialized, dynamic). In this vast group of languages only a handful have been labeled as “Java.next”, in other words, those capable of becoming the next mainstream JVM language other than Java itself. Groovy and Scala belong to that group.
Groovy brings to the table modern features such as closures, native syntax for Maps and Lists, regular expressions as first class citizens, optional typing, metaprogramming capabilities; and perhaps most importantly, seamless integration with the Java language. A Groovy class is a Java class, the opposite is also true. A Groovy method is also a Java method, the opposite is again also true. Furthermore, the Groovy compiler comes with a joint compilation mode, allowing you to compile Groovy and Java sources at the same time. This is a very handy feature, especially when those sources reference one another, say a Groovy class implements a Java interface that collaborates with another Groovy class, you get the idea.
Scala on the other hand is a language that was designed from the ground up to be a replacement for Java. It comes with its own data types, an extensive type system, a type inference aware compiler, immutable and mutable collections, functions (closures if you will), and a few other golden nuggets. Scala's style is a marriage of object oriented and functional. The Scala compiler recently received a face lift, it is now able to joint compile Scala and Java sources as well, similarly as the Groovy compiler. While a Scala class can be compiled to a Java equivalent, meaning that you can call Scala from Java as if it were plain Java, some Scala methods have a shorthand naming convention that make them look ugly when called from Java.
All that being said, Scala offers some advantages over Groovy. Its functional style is complemented by immutability constructs baked right into the language; in fact immutability plays a big role in Scala's design. Another factor is its type inference mechanism. For those that believe that static typing is a safety net that must always be present, then this feature makes working with types more palatable. Simply put, it offloads a lot of work done by your brain and fingers and puts it where it belongs: the compiler. Lastly, Scala code runs faster than Groovy (understandable given that Groovy uses dynamic method dispatch), sometimes Scala code runs even faster than Java.
Now comes the question, which is more suitable for your next project, Groovy or Scala? Honestly there is no single answer that satisfies everyone. Chances are there is some portion of your application that could benefit from Scala's functional style, while dynamic DSLs with Groovy could solve a problem on other portions. Instead of biting the bullet and going with one language or the other, let's go with both! These are modern JVM languages after all, surely there are a few tricks that can be applied to have them both communicate in a friendly manner.
Java as a Middle Ground
Our first approach to polyglot nirvana will be the Java language itself. Groovy not only is able to call Java in a seamless way, it can also implement Java interfaces and extend Java classes. Well what do you know, Scala can do that too without breaking a sweat! Armed with this knowledge it would be a simple matter to design a set of Java interfaces/classes that can be implemented/extended/referenced from both Groovy and Scala. Let's look at a simple example, Listing 1 shows a run-of-the-mill Java interface.
Listing 1: Greeter.javaListing 2 is a bare-bones implementation of the Greeter interface in Groovy.
Listing 2: GroovyGreeter.groovyYou can compile both sources in the same step by issuing the following command:
Compile the Scala source with the following command:
$ scalac -cp $GROOVY_HOME/embeddable/groovy-all-1.6.4.jar:. Test.scala
Finally run it by typing the following on your command prompt
$ scala -cp $GROOVY_HOME/embeddable/groovy-all-1.6.4.jar:. Test Hello Scala from Groovy!
Granted, this example is quite simple, some would even say that by virtue of Scala's type inference we wouldn't need to define the type for the greeter variable. For example, just imagine that the value comes from a factory or an IoC/DI container, then it makes perfect sense to leave the type. This is how things would look like if the roles were reversed. First a Scala based implementation of the Greeter interface, as demonstrated by Listing 4.
Listing 4: ScalaGreeter.scalaNext the “business” end in Groovy shown in Listing 5.
Listing 5: GTest.groovyCompile and run the additional sources with the following commands:
$ scalac -cp $GROOVY_HOME/embeddable/groovy-all-1.6.4.jar:. ScalaGreeter.scala $ groovy -cp $SCALA_HOME/lib/scala-library.jar:. GTest.groovy Hello Groovy from Scala!
That wasn't so bad, was it? The added benefit is that you can send either implementation of Greeter to any method that accepts a Greeter and it will work, no matter in which language that method was written.
But we can do better than this, let's cut the middle man out and have both languages talk to each other directly.
Groovy calling Scala
Groovy is quite happy handling Scala code, it will do it in the same way as it handles Java code. But if your intention is to harness the power of a particular Scala library then you might be in for a surprise. Let's say for the sake of argument that you need to deal with Scala's collection library. As mentioned before, these collections come in two flavors: mutable and immutable, with the latter being the preferred ones. Scala collections have plenty of useful methods that simplify your code, however those collections cannot be interchanged with Java/Groovy collections, they have their own independent hierarchy (by design). This can be troublesome as pretty much all Groovy additions to JDK Collections are not visible in Scala collections. Furthermore those handy collection methods that rely on Scala's functional style require you to send them a Function object, not a Groovy closure.
If only there was a way to enhance a class with new behavior... oh wait, but there is! The Groovy MOP (Meta Object Protocol) can take care of this issue in an elegant manner.
We will start by defining the domain. Listing 6 shows a Scala class that defines 4 methods (though for Groovy eyes they look more like properties don't they?)
Listing 6: ScalaBean.scalaThe first 2 methods return an instance of scala.List, the last 2 methods return an instance of scala.Function1. It is worth noting that if you ever try to apply sfun to ilist from Scala the compiler will not let you proceed, because the types don't match.
Alright, here comes the first trick, a target class requires a single method in order to take advantage of the so-called iterator methods that Groovy adds to the JDK, That method must comply with the following signature:
java.util.Iterator iterator()
Yes, it is that simple. Now it is a simple matter of finding a java.util.Iterator friendly method on a Scala List. Sadly there is no such method but there is one that returns a scala.Iterator, maybe we can wrap that with our own implementation of java.util.Iterator. We also need a way to attach the new method to a scala.List, this task can be easily achieved via its MetaClass. Listing 7 demonstrates how it might be implemented.
Listing 7: ScalaClasses.groovySweet! With this setup we're now able to make the following calls from a Groovy script as shown in Listing 8.
Listing 8: GroovyScala.groovyOnce the new iterator() method has been added all other iterator based methods will work as expected. You can certainly use find(), grep(), findAll(), any(), each() and every other iterator based method with confidence now.
Let's turn our attention to Functions & Closures. Functions in Scala are defined by interfaces. Each interface defines 3 methods: curry(), toString() and apply(). Each Function interface has a different signature for apply(), related to the number of arguments it can process. For example, scala.Function0 defines apply() but scala.Function1 defines apply(Object). We must be careful with the number of arguments accepted by each function when transforming a closure into a Function, the same rules apply in reverse. Luckily for us Groovy knows how to handle variable arguments, as shown by the helper class in Listing 9.
Listing 9: ScalaFuns.groovy (update 1)We leave the implementation of curry() empty for now, after all this is a first approach to language interoperability, it is definitely far from finished. Transforming a closure into a function will work provided you do not define more than 22 arguments (there is a Function22 class but there isn't a Function23) and that function is not curried afterwards. The reverse operation, function to closure, is achieved by wrapping the function with a closure that takes variable number of arguments (varargs for short). Notice there is no particular type defined for the function variable. The spread operator will take care of expanding the argument list, thus the correct apply() method should be called. With this helper class we're now able to make the calls from a Groovy script as seen in Listing 10.
Listing 10: GroovyScala2.groovyThe map() function is a method defined in scala.List. It takes a function as parameter and applies it to each element on the list, returning a new list with each transformed element, in other words, it’s pretty much collect()'s twin. First we check that map() works as expected when passed a function as an argument, then we convert a closure (named mapper) into a function, map it again and check results. Because Groovy is happy with duck typing only one mapper closure was required. Lastly we use Groovy's collect() method with the mapper variable and transformed function.
Naturally this is just the tip of the iceberg. Similar steps can be replicated to enhance other Scala collections, like Maps, Sets and Sequences. That however, is left as an exercise to the reader. Who knows, maybe somebody will come up with a library that eases up interoperability from Scala to Groovy.
Let's take a look at the other side of the coin, shall we?
Scala calling Groovy
It turns out Scala is also quite happy calling your Groovy code as if it were Scala code. The problem comes when you want said Groovy code to be used with idiomatic Scala, it simply won't work all the time. Just like Groovy, Scala supports properties out of the box, but with a different set of conventions. Listing 11 shows a simple class with a single property.
Listing 11: Bean.scalaWhen compiled, the Bean class will look like the snippet shown below
javap Bean Compiled from "Bean.scala" public class Bean extends java.lang.Object implements scala.ScalaObject{ public Bean(java.lang.String); public void name_$eq(java.lang.String); public java.lang.String name(); public int $tag() throws java.rmi.RemoteException; }
It's true, in Scala the Bean class fits in a single line. Notice the naming convention for its name property. You can be sure that every property on every Scala bean follows the same convention. Imagine writing those property accessors by hand, surely there is a better way: the AST Transformations framework.
Introduced in Groovy 1.6, the AST Transformations framework includes compile time metaprogramming capabilities to the Groovy language. With it you'll be able to tweak a class at compile time by doing things such as adding new methods, removing unwanted code and so forth. Writing an AST Transformation is a hard task, frankly a bit daunting too, but the rewards are worth it. But let's not get into the gory details this time, for now you only need to know that an AST Transformation requires a marker interface. This interface can be used to inject metadata that the AST processor requires to do its work. There a few standard AST Transformations which come bundled with Groovy, like @Delegate, @Bindable and @Lazy. [See Guillaume Laforge's “What's new in Groovy 1.6” in GroovyMag April 2009 for more information]. However there is an additional module that serves as an incubator for non-standard AST transformations called Groovy Transforms, it so happens to provide @Scalify, just what we need
Any Groovy class annotated with @Scalify will generate the required boiler plate code to make it friendlier to Scala when compiled. In its current release @Scalify will generate property accessors that follow the Scala conventions. It will also generate operator overloading methods that follow the Scala conventions too. Listing 12 shows an example of Groovy bean which is annotated with @Scalify.
Listing 12: GBean.groovy
Once compiled it will generate the following bytecode:
$ groovyc -cp $SCALA_HOME/lib/scala-library.jar GBean.groovy $ javap GBean Compiled from "GBean.groovy" public class GBean extends java.lang.Object implements scala.ScalaObject,groovy.lang.GroovyObject{ // ... snip public GBean(); public GBean plus(GBean); public GBean $plus(GBean); public void name_$eq(java.lang.String); public java.lang.String name(); public int $tag(); public java.lang.String getName(); public void setName(java.lang.String); // ... snip }
The previous command assumes you placed the groovy-transforms-0.1.jar into $GROOVY_HOME/lib. As you can see, the GBean class contains both valid Groovy byte code and valid Scala byte code. There is a catch however, and it has to do with how Scala manages signatures. Even though the byte code appears to be correct, if you attempt to call the Scala friendly setter from Scala using it's short notation, i.e, by calling gbean.name = “Foo” instead of gbean.name_$eq(“Foo”), the Scala compiler will complain about a missing method! This happens because the Scala compiler performs an additional step while working, it creates a class attribute named Pickle and attaches it to the generated byte code. This attribute contains the signature for each method, and it is used by the compiler to verify the code while compiling (among other things). The @Scalify AST transformations doesn’t generate a pickle (update 2) attribute at the moment. Hopefully this missing feature will be provided in a future release.
Can Scala quack?
There is one last option left to explore. Scala can let your dogs, cats and ducks quack even though Scala is statically typed. What you will see next is Scala's last resort to duck typing: structural types.
Essentially, if you cannot know in advance what type of object you will be receiving, at least constrain its behavior to a predefined set of methods. Be warned that this feature relies heavily on reflection, many Scala developers shun it away for performance reasons.
First, let's define two Groovy classes that share a method signature, say Human (Listing 13) and Robot (Listing 14), both should be able to get some work done, right?
Listing 13: Human.groovyListing 14: Robot.groovy
We will continue with the example despite our Human class not being very helpful. We need a place for both humans and robots to do some work, a factory would be perfect. However the people in charge of the factory don't care who performs the job as long as the work gets done, so the Factory (Listing 15) simply hands a task to the next worker.
Listing 15: Factory.scalaBelow is some sample output of running the code once:
$ scalac -cp $GROOVY_HOME/embeddable/groovy-all-1.6.4.jar Factory.scala $ scala -cp $GROOVY_HOME/embeddable/groovy-all-1.6.4.jar:. Factory Robot@11e0c13 bzzzt * click ... wheee .. bzzzt Human@1d2b01b *need coffee break*
There you have it. A word of caution, not only are structural types a sure hit on your application's performance (when compared to regular Scala code) but they can get in the way once additional signatures are required, the usage of Traits or plain Java interfaces is recommended instead.
Conclusion
Using more than one language to develop an application is a growing trend, the main reason being that there is no silver bullet; there is no single language that can solve all problems. Mixing Groovy and Scala makes perfect sense if what you need is better performance, a functional style for developing algorithms and very flexible DSLs. Hopefully this article tickled your curiosity to learn more about each language and test them out together.
Update #1: Groovy 1.7 (recently released) supports anonymous inner class definitions. The usage of a runtime proxy may not be needed anymore.
Update #2: I've been told that the upcoming Scala 2.8 release does not require a Pickle.
Keep on Groovying!

About Andres Almiray
Andres is a Java/Groovy developer and a Java Champion with more than 20 years of experience in software design and development. He has been involved in web and desktop application development since the early days of Java. Andres is a true believer in open source and has participated on popular projects like Groovy, Griffon, and DbUnit, as well as starting his own projects (Json-lib, EZMorph, GraphicsBuilder, JideBuilder). Founding member of the Griffon framework and Hackergarten community event. https://ch.linkedin.com/in/aalmiray
Why Attend the NFJS Tour?
- » Cutting-Edge Technologies
- » Agile Practices
- » Peer Exchange
Current Topics:
- Languages on the JVM: Scala, Groovy, Clojure
- Enterprise Java
- Core Java, Java 8
- Agility
- Testing: Geb, Spock, Easyb
- REST
- NoSQL: MongoDB, Cassandra
- Hadoop
- Spring 4
- Cloud
- Automation Tools: Gradle, Git, Jenkins, Sonar
- HTML5, CSS3, AngularJS, jQuery, Usability
- Mobile Apps - iPhone and Android
- More...