Wednesday, May 9, 2012

Scala vs Java Code Example

I hope "Why Scala?" article sparked enough interest to actually dive into some code.

Here is a Scala vs Java code example from stackoverflow:

up vot40down voteaccepted
Let's improve stacker's example and use Scala's case classes:
case class Person(firstName: String, lastName: String)
The above Scala class contains all features of the below Java class, and some more - for example it supports pattern matching (which Java doesn't have). Scala 2.8 adds named and default arguments, which are used to generate a copy method for case classes, which gives the same ability as the with* methods of the following Java class.
public class Person implements Serializable {
    private final String firstName;
    private final String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;

    public String getFirstName() {
        return firstName;

    public String getLastName() {
        return lastName;

    public Person withFirstName(String firstName) {
        return new Person(firstName, lastName);

    public Person withLastName(String lastName) {
        return new Person(firstName, lastName);

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        if (o == null || getClass() != o.getClass()) {
            return false;
        Person person = (Person) o;
        if (firstName != null ? !firstName.equals(person.firstName) : person.firstName != null) {
            return false;
        if (lastName != null ? !lastName.equals(person.lastName) : person.lastName != null) {
            return false;
        return true;

    public int hashCode() {
        int result = firstName != null ? firstName.hashCode() : 0;
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        return result;

    public String toString() {
        return "Person(" + firstName + "," + lastName + ")";
Then, in usage we have (of course):
Person mr = new Person("Bob", "Dobbelina");
Person miss = new Person("Roberta", "MacSweeney");
Person mrs = miss.withLastName(mr.getLastName());
val mr = Person("Bob", "Dobbelina")
val miss = Person("Roberta", "MacSweeney")
val mrs = miss copy (lastName = mr.lastName)
link|improve this answer

You can run this Scala code online using or, which also has interactive Scala tutorial included.

There are Scala IDEs for Eclipse, NetBeans, IntelliJ IDEA, Emacs, etc. An interesting option is Kojo ( - Scala for Kids.
Lalit Pant, volunteer Math teacher at Himjyoti School for under-privileged girls in Dehradun, developed Kojo in his 'free' time. Kojo is a very polished, easy to install, cool IDE in which children, (or even grown ups) can learn to program using Scala. Lots of examples, a turtle to drive, good documentation and interactive geometry for those budding mathematicians. If you have kids then Kojo could be a fun experience to share with them.

For Java programmers I recommend reading quick "Roundup: Scala for Java Refugees".
You know who you are. You’re the developer who picked up Java years ago, maybe as a second language and better alternative to C++, maybe as your first language coming into the industry. You’re comfortable with Java, you know its ins and outs, its moods. It’s like an old girlfriend; you may not feel the vibe anymore, but you know just how to rub it so it smiles. In short, you’re a craftsman, and Java is your workhorse tool.
You’ve heard of this new-fangled thing called Ruby - how could you not have heard, given the sheer noise level produced by its followers. You’re impressed by the succinctness of its constructs and the power of its syntax, but you’re not sold on the idea of using a scripting language to build your enterprise app
The good news is that there’s light at the end of the tunnel. There’s a new language on the scene that’s taking the developer world by storm. Scala seems to offer everything you’ve been looking for in a language
The only problem you have now is figuring out where to start.
Have no fear, ye refugee of Java EE grid iron, all is not lost... you don’t have to write code with the sole purpose of pleasing Haskell Curry... You just need the right introduction.
I personally have very little FP (Functional Programming) experience, so I don’t think I could write an article about porting Scheme code to Scala even if I wanted to. Instead, this series will focus on how Scala is just like Java, except better.

There are even free books among 27 books written about Scala so far.
  • Free On-Line Books on Scala
    A free sample of Scala for the Impatient, a book written by Cay Horstmann is available from Typesafe for download. A very practical book for developers with Java experience learning Scala. O'Reilly has made Programming Scala, a book written by Alex Payne and Dean Wampler freely available on-line. This comprehensive book will appeal to experienced programmers wanting to learn Scala. It is packed with examples and clearly explains in a pragmatic way most of the more advanced features of Scala.

  • "Programming in Scala," 2nd ed., by Martin Odersky, Lex Spoon, and Bill Venners
    This is the award winning, authoritative book co-written by Scala's designer. The second edition comes with more than 100 pages of new material covering new features in 2.8, while the first edition of the book has been made freely available. For more on this and other books, see the list of available Scala books.

The particular Scala vs Java code example from this article is not as important as the difference in mindsets underlying the languages. You can find one more code example in the next article, which should give you more clue of what I mean.

No comments:

Post a Comment