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

The Adventurous Developer’s Guide to JVM languages – Xtend

Yesterday, Anton published a really interesting overview of Ceylon, the JVM language from RedHat. This blog post will focus on Xtend, the language which self-proclaims itself as ‘Modernized Java’. The language seems to place itself as ‘faster than Groovy, simpler than Scala and incorporates all the benefits of Java’.

xtend-logo

The language is built on top of the Xtext language development tool, which gives it great integration with the eclipse IDE. Yes, this time I chose wisely! I have picked a language which has tooling on my IDE of choice, eclipse! Well it’s not hard to see why, as both Xtend and Xtext are eclipse projects! Other IDE fanboys (Anton) will not get tight integration with their IDE of choice, similar to Kotlin preferring IntelliJ IDEA. That’s a real shame as it really limits your audience. Would you say you’re more likely to try out a new language if support exists in your favoured IDE? Let us know in the comments below.

As with previous posts, I have constructed an HTTP Server sample in the JVM language we’re talking about, and you can view my source on github. Again, please feel free to comment, suggest/submit pull requests – We’re always happy to learn and see improvements.

On your marks, Get set, Code!

Go go go! Straight into Eclipse and get some code down… hey, this is actually quite familiar coding (as a Java developer). The Xtend language syntax has remained fairly true to Java, which could be considered a good or a bad thing, depending on your impressions of the Java syntax :) Yes it is simpler as the the usual Java baggage has been removed (as with most new langs) leaving the code more readable and only using structure and keywords where needed, leaving us with a readable, cleaner, implementation. Lets take a look as some code:

package com.zt
 
class Oppa {
 
	def static void main(String[] args)
	{
		println('Gangnam, Style')
	}
}

Note I promised in a previous post we wouldn’t look at “Hello, World” examples, so here is my “Gangnam, Style” example :) So far we see very little has changed from Java, but one thing I do notice in my IDE is an xtend-gen source folder which has interpreted my Xtend code into Java code:

package com.zt;
 
import org.eclipse.xtext.xbase.lib.InputOutput;
 
@SuppressWarnings("all")
public class Oppa {
  public static void main(final String[] args) {
    InputOutput.<String>println("Gangnam, Style");
  }
}

Interestingly it pulls in it’s own println implementation via the InputOutput Xtend class.

Overall in my Xtend HTTP Server sample, I wrote 137 lines of code, which was translated into 309 lines of Java. The Java created isn’t particularly readable and I wouldn’t particularly want to edit it, so I’m not really sure why it’s shown. Amusingly at one stage I got into a state where my Xtend code compiled yet my Java code did not :) This was all down to ‘fun with arrays’ and deserves it’s own section!

Fun with Arrays!

Arrays can be used, but you cannot directly instantiate them like you would in Java – byte[] bytes = new byte[]{0,1,2}. Instead you use ArrayLists and create them using val items = newArrayList(0,1,2). You can access them using items.get(1), instead of the more familiar Java – bytes[0]. Some people I would imagine love this, I actually prefer the way Java does this, and really got in trouble when I was trying to create a byte array of a certain size to fit the bytes of the requested file into. Xtend coverts from one to the other under the covers. I tried an implicit cast in Xtend which the Xtend compiler loved, but once this was translated into Java, I got my Java compile time warning so needed to perform my explicit cast, as byte[]", for this to work. So what did I do to fix it? What everybody should do in this instance, use FileUtils from the Apache Commons IO library! I added a new topic to the Xtend forum to understand how to do this though.

What can I do with Xtend that I can’t do with Java?

This is where it gets interesting, as Xtend provides many of the features which Java lacks. For instance, it provides extension methods, import extensions, lambdas, @Data set objects, implicit typing and more. This is great! But I could have listed almost all of these off in my Kotlin post as could Anton in his Ceylon post. What makes this language any different? Well it’s not trying to be different, it’s trying to bridge a gap between where Java is now and where IMO it should be. It’s Java on steroids.

Code snippets

Enough talk already! Need more pictures and code! Lets dive into some of the neat parts of the language, starting with extension methods.

Here we’re creating a new method called sendHtmlResponse which takes 4 parameters, however there is a neat syntactical trick here which allows the first parameter to also be the object we’re trying to extend.

    def sendHtmlResponse(Socket socket, String status, String title, String body){
        val html =
'''<HTML>
        <HEAD><TITLE>«title»</TITLE></HEAD>
        <BODY>
            «body»
        </BODY>
</HTML>'''
 
        socket.sendHttpResponse(status, "text/html", html.toString.getBytes("UTF-8"))
    }

This means we could actually call sendHtmlResponse on the Socket object.

    socket.sendHtmlResponse(
        "HTTP/1.0 404 Not Found",
        "File Not Found",
        "<H2>404 File Not Found: " + file.getPath() + "</H2>")

Of course in our xtend-gen directory, we’re actually generating Java code which looks like this:

    this.sendHtmlResponse(socket, "HTTP/1.0 404 Not Found", "File Not Found", _plus_3);

While this spoils the illusion, it is really nice to be able to extend classes and this is in fact where Xtend gets it’s name from.

In our first code snippet we used the following construct:

'''<HTML>
        <HEAD><TITLE>«title»</TITLE></HEAD>
        <BODY>
            «body»
        </BODY>
</HTML>'''

This is called a template expression and is used in many other languages, such as Kotlin. It allows us to easily create HTML without tripping over out.println() statements, allowing us to better see what kind of doc we’re creating. You’ll notice we can escape the statement to drop in variables, and you’re also able to use conditionals in the templates.

I did miss named parameters and defaults from Kotlin among others, which I still think just should be a part of all languages! It does make use of implicit typing though which was nice. The language is still statically typed but the type of a variable is determined at compile time by the value of the expression it will be assigned. For example:

    val WEB_ROOT = "."
    val DEFAULT_FILE = "index.html"
    var Socket socket

In this example the first two variables are clearly Strings, whereas the third cannot be determined at this point, so we need to declare its type is Socket. This makes the code a lot clearer compared to the following in Java:

    private final String WEB_ROOT = ".";
    private final String DEFAULT_FILE = "index.html";
    private final Socket socket;

Some of the more syntactical differences took more than a second or two to work out, like ‘Where have my class methods gone!!’ :o) Oh, you have to use a different notation to get that – File::separator. I’m not really sure why this has been imposed but it’s not a big issue so didn’t bother me too much.

Interestingly the issues I had with fixing Kotlin compile issues, whereby the IDE would complain about a million things when there was only one problem, also occurred in Xtend. This is quite frustrating as you have to fix things in the order the Xtend compiler wants you to, rather than the order you want to. Java tooling support still wins on this topic.

Java Interoperability

While many languages struggle to achieve Java interoperability, Xtend really doesn’t share their problems as they share a near identical type system proving an easy mapping to and from the languages. You’re able to directly call from Xtend to Java and vice-versa without issues. Enough said.

Summary

I enjoyed learning and using the Xtend language a lot, due to the concise neatness it provides with the functionality which Java promises for the future but currently lacks. The question is, would I recommend others to use it over and above Java or other JVM languages? Well, for Java users it’s all going to depend on how long these benefits last for, as once some of the nice feature additions in Xtend make it into the Java language, just as lambdas and method extensions, I’m not sure there’s enough to justify the move. I imagine developers using other JVM languages such as Scala see Xtend more as Java n+1 or Java with a plugin rather than a language which breaks any boundaries, so I don’t see why Scala users might break away to use Xtend. Don’t forget to check out my source on github and feel free to suggest/submit pull requests!

This is the third blog post on JVM languages and already we’re noticing there are many features that are similar across the set, with some structural differences while others are more cosmetic. History has given us a graveyard of languages that weren’t good enough or applicable enough to for developers of the time. There’s even an acronym, YAJL, that stands for Yet Another JVM Language! With so many languages already around, will the graveyard become overpopulated? A danger exists that with so much choice in the market, many languages will fall quickly with others not getting enough attention or contribution as the resource is spread thinner across languages.

options

My opinion is two fold; I’m a great believer in creating and innovating and this can very often come from a project starting from scratch as you drop existing concepts and designs, so that thought can begin on a blank canvas. As an industry, we don’t want to cap new projects or initiatives as that’s often how we find new directions, but I do think where we can make a difference to existing languages we should help existing languages. What do you think? Would you prefer a language more suited to your individual preference with fewer people behind it or a larger backing with them into more general user experience?

Psst! If you liked this post, we wrote a 50-page RebelLabs report on Java 8, Scala, Groovy, Fantom, Clojure, Ceylon, Kotlin & Xtend.

Get the FULL REPORT on all 8 JVM languages


  • py

    Why we need yet another JVM based language? What is new here in comparison to eg. Groovy?

  • c_world_poster

    py – because the devil (or savior?) is in the details. Xtend is not just another language.

  • arhan

    Language design is an experiment and a set of trade offs. Groovy compiles to bytecode and xTend translates to Java – that’s already a big difference.

  • arhan

    What is xTend then? :) The same can be told about any other language out there – Scala, Groovy, Fantom, MIrah – not just another language.

  • http://twitter.com/sjmaple Simon Maple

    Hey py, thx for the comment. The JVM is a stable platform that gives languages based off it many services, most notably a gc and highly performant and tuned core. For me it’s quite clear why someone might choose to base their new language on the JVM and why many port their langs to the JVM. If your comment is about why we need more langs in general, my opinion is in the summary of the article. As Anton mentions there are notable differences to groovy.

  • http://twitter.com/sjmaple Simon Maple

    Hey, thx for your comment. Which features/details of Xtend, for you, make it stand out above other langs? What would make you use it?

  • c_world_poster

    A few things:

    It has tooling support out of the box
    It is built “on top” of the Java language.
    One doesn’t have to recreate all of the Java APIs or find work arounds because it works

  • c_world_poster

    RIght. They have their different approaches and thus pros/cons.

  • bob

    My company is considering to adopt Scala as its quite popular now and designed by a very well known designer of Generics and new Javac. This article caught my attention with Xtend. It sure sounds interesting !! Though this article claims it to be better then Scala has yet to me tested by me but what is fascinating is it compiles into Java code unlike Byte Code as Scala or groovy…it means even a lot….i.e you may program at your will in Xtend and then later may even tweek in the compiled java code in your own syntactical preferences , so if your company want you to just stay on plain old Java still , programmer can write in Xtend and commit the generated code to SVN..cool..so for me it looks like a java tool in my hand!!!

  • Pou

    Please lose the VERY FUCKING ANNOYING floating icons on the left!