Imagine a bacon-wrapped Ferrari. Still not better than our free technical reports.
See all our reports

A Month of JVM languages: Groovy, Ceylon, Kotlin and Scala

the-next-jvm-language-to-learn-graph

The month of December provided Virtual JUG members, vJUGers, with great insight from language creators, product leads and advocates about what else is available for them to use outside of the Java language, but remaining on the JVM.

We’ve touched the topic of alternative JVM languages multiple times now. The Java Tools and Technology report established what languages are considered to be more lucrative to learn, and had a deeper dive into the technical details of those in the Adventurous Developer’s Guide to JVM Languages report. However, it is one thing to hear about the languages from us, and a completely different thing to listen to the language designers talk about the most interesting features of a language and design decisions made to make these possible.

It was also really great to watch and discuss the sessions in the IRC chat and see what people thought about established languages such as Groovy and Scala as well as new, upcoming languages like Kotlin and Ceylon. In this post, I’ll try to talk about my top 2 features of each language we covered on the vJUG.

You can treat yourself to watching them all the sessions in full by clicking your preferred session below. It will be a nice distraction from watching a countless run of Die Hard.

For the impatient or those, who didn’t have time to tune in for live presentations, here are the links to the recordings:

Shameless plug: By the way, I know you want to hold the fancy title of vJUGer, so waste no time and come join us at Virtual JUG. You won’t regret having access to consistently great sessions from the world class speakers.

Groovy

There are plenty of differences between Java and Groovy which make Groovy more pleasant language to develop in, as it reduces huge amounts of boilerplate code including no semi colons, no getters/setters, type inference, null safety, elvis operators and much much more. That’s not to say you’re not permitted to use Java notation if you so choose, though. Interestingly most Java code will compile in groovy so it has a low bar for entry into the language.

Polymorphic Closures

The first point which I felt was really great in Groovy was Polymorphic Closures. This is the ability to write a closure, or a function if you prefer to call it that, without specifying the type of the parameters. This means, that so long as the types you call the closure with can deal with the behaviour in the body of the closure expression, your code will run. Consider the following:

def adder = { a, b -> a + b }
assert adder(1, 2) == 3
assert adder(‘a’, ‘b’) = ‘ab’

Here we define a closure and assign it to adder. We don’t specify the types of a and b, but the body of the closure adds them together, so the parameters must be suitable to pass to the plus operator. We can now pass different sets of parameters to the adder closure, so long as they’re suitable for addition together. This is achieved via a mix of duck typing and operator overloading.

Power asserts

Don’t you hate it when().you().have().a().big().line().of().code().with().a().bug() but have no clue where in the like it comes from?

Yeh, me too. Some might say it’s bad coding taking this to the extreme, but Groovy here wouldn’t just tell you about a NullPointerException on a line, but it would go into detail about which part of the line caused it. Power asserts go further, they don’t just tell you there’s a problem, in your expression, but they also break the expression down and show you the values in each of the subexpressions!

If you haven’t seen it before, here’s an example that can blow your mind:
groovy-asserts


Are you intrigued yet? Check out the full vJUG session: Groovy for Java Developers by Guillaume Laforge:

Ceylon

Like Groovy, Ceylon delivers on the ‘easier to code than Java’ front with much less ceremony and boilerplate code in general, including many of the same groovy like features. However Ceylon dares to be different and really looks at the playing field from scratch, including the type system itself. Here are my top two favourite features from the Ceylon language.

Modules

Firstly, we’ll start at modularity. An area which has troubled the Java space (particularly the implementers) with how it should be implemented and which release it will fit in. Ceylon has the luxury of starting from the ground up, so can make their decisions on how they want their language future to look, with less emphasis on the past. In Ceylon, your code resides in a module with a file which states the name and version of the module. You are able to import other modules and even make your module available on the Ceylon herd, the official Ceylon module repository, for other Ceylon developers to make use of it – neat!

But you can share libraries like that, right? Sure, but where this really comes into its own is when we talk about runtime! We’re effectively wiring up modules here and creating a much tighter classloader pattern, similar to how OSGi works, I guess. What does that give you? Well, I’m sure you’ve heard of the dark lonely place that is JAR hell, where you have multiple versions of classes in multiple places on the same classloader path – eek, bet you wish you had a modular runtime now!

Union types

When’s an Integer not an Integer? When it’s a Float! Hahaha. Ok, it’s not that funny, but one thing Ceylon introduces is the idea of a Union type system that allows you to group types. Let’s look at an example.

ArrayList<Integer|Float> list = ArrayList<Integer|Float>(1, 2, 1.0, 2.0)

And if I choose to grab an element of the list, it’s type is:

<Null|Integer|Float> it = list[2]

Where Null is included in case the lookup was out of range.


Check out the full vJUG session: Ceylon for Java Developers by Gavin King.

Kotlin

Kotlin is a relative newcomer of a language and is similar in age to Ceylon. It takes a lot of influence from Scala and C# and again inherits many of the nice syntax enhancements Java is stuck with. Here are my two gems.

Data Annotation Class

In Kotlin you can define a class very simply:

public class CustomerKotlin

In fact, that’s all you really need! Yep, no need for a body even, if you don’t want one. Let’s create some more, by adding a constructor and some variables.

public class CustomerKotlin (var name:String, var email:String, var country:String)

We’re using something here called primary constructors where our method parameters in our constructor is marked as var (a mutable type, val is immutable by the way) and is a field on the class.

If we add a new function and create a couple of instances of these objects for equality, we’ll notice they’re actually different instances, as you’d expect.

public class CustomerKotlin (var name:String, var email:String, var country:String)

  fun main(args: Array<String>) {
    val customer1 = CustomerKotlin(“Simon”, “simon@zeroturnaround.com”, “UK”)
    val customer2 = CustomerKotlin(“Simon”, “simon@zeroturnaround.com”, “UK”)
    
    if (customer1 == customer2)
      println(“The Same”); // won’t print
  }

By annotating the class with the data keyword, we turn it into a Data Annotation Class, which implements hashcode, toString and equality. This means the following will pass the if branch and print out “The Same”:

data public class CustomerKotlin (var name:String, var email:String, var country:String)

  fun main(args: Array<String>) {
    val customer1 = CustomerKotlin(“Simon”, “simon@zeroturnaround.com”, “UK”)
    val customer2 = CustomerKotlin(“Simon”, “simon@zeroturnaround.com”, “UK”)
    
    if (customer1 == customer2)
      println(“The Same”); // will print
  }

Sounds confusing to debug? Possibly, but it’s extremely powerful!

Extension functions

I always like method extensions as it makes code very easy to read. Here’s an example. If I take a type, I can extend it with a method call very simply by using the type name followed by .methodName in my code. Here’s a simple example.

fun String.helloWorld()
{
  println(“Hello, World!”)
}

This simple example means that for any String type, I can now call the helloWorld method on that type and the method I just wrote will be called. You can do very similar for extending a class to add a field too.


Continue to watching the full vJUG session: Kotlin for Java Developers by Hadi Hariri.

Scala

Scala is considered to be the alternative JVM language to learn. And I have no doubt that you’ve heard of it and saw tons of examples before. Here are two features that never cease to amaze me, when we talk about Scala.

Case class

If I wanted to create a class called person which has a name, there are no automatic getters that are created, so I’d need to update the object with a bunch of code to fix that. However, if I used a case class an amount of code generation is done for me. Here’s an example in the Scala REPL:

scala> case class Person(first: String, last: String, age: Int)
defined class Person

scala> val harry = Person(“Harry”, “Potter”, 29)
harry: Person = Person(Harry, Potter, 29)

Now even though I haven’t defined a getter, I can retrieve the first name as follows:

scala> harry.first
res10: String = Harry

I can also copy and make changes to the immutable values as follows

scala> harry.copy(age = harry.age + 1)
res11: Person = Person(Harry, Potter, 30)

Next, and one of the more interesting methods added by the case class is the ability to use in-depth pattern matching. Case classes have extractors added, which is what the match functionality uses in it’s pattern matching.

Future

Futures are a great non blocking way of getting work done in parallel, but what impresses me is the simplicity in the code. Check out this function:

def SlowRandInt() = Future {
  Thread.sleep(20000)
  Random.nextInt(20)
}

This is a simple function that represents an operation that take approx 20 seconds to execute. More interestingly though, it returns a type of Future, which means the code will be executed on a new thread taken from a thread pool. The next thing to do is create three futures and do something with them.

val f1, f2, f3 = SlowRandInt()
val r1 = for {
  i1 <- f1
  i2 <- f2
  i3 <- f3
} yield i1 * i2 * i3

Now, none of these steps are blocking and r1 will be created instantly as a Future and will initially be of type None (Scala equiv of null). After approx 20 seconds the value of r1 will be the result of the multiplication of the three random numbers.


Here is the full vJUG session: Scala for Java Developers by Dick Wall.

Conclusion

All in all, Groovy, Ceylon, Kotlin, and Scala are all great languages that it’s super fun to take time out and have a play with.

If you’re a Java developer, I think you’ll really enjoy some of the new features that most share, including names and default parameters, multiline strings, the list really does go on. My recommendation is that you should pick one and use it for your next hobby project for sure and see how you get on. Don’t forget to check out and bookmark for later the full videos on the vJUG site:

And for more details on these and more languages, we have our full RebelLabs report on JVM languages available!


It's right here: JVM languages report

 

  • Niedermeier Josef

    good article, thanks
    just typo in the Scala Future example

    should be
    yield i1 * i2 * i3
    instead of
    yield i1 * 12 * 13

  • Camilo A. Navas

    “Now, none of these steps are blocking and r1 will be created instantly as a Future and will initially be of type None (Scala equiv of null). After approx 20 seconds the value of r1 will be the result of the multiplication of the three random numbers.”

    That’s wrong, None is a subtype of Option and Future is no subtype of Option. It will just be a future whose “isCompleted” will return false, and 20 secs after, if called, will return true. Futures actually wrap an object of class “Try” (whose subtypes are Failure and Success)