« Posts under Scala

Scala – New alternative to Java!

SCALA to quote the scala website found here:

“Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. It is also fully interoperable with Java.”

In other words if you are a Java programmer like myself & you find yourself looking at your code and saying “I wonder if I could make that smaller” then Scala is the language for you!

The Scala syntax has several “shortcuts” that allow very clean & simple code that still greatly resembles Java syntax. So if you are a Java programmer you should be able read Scala code without looking much up. Anyway the best way to demonstrate this is by showing some actual Java & Scala code side by side.

So here is the code example for a very simple & boring “Hello World” style program!:

JAVA
public static void main (String [] args) {
    System.out.println("Welcome to My Small Corner Of The Web!");
}

SCALA
object HelloWorld extends Application {
    println(”Welcome to My Small Corner Of The Web!”)
}

So here we can see that even for just a simple program that the Scala syntax is a lot simpler. A better example to show the Scala power is shown below:

JAVA
public class Name {
    private String firstName, lastName;

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

    public String getFirstName(){
        return firstName;
    }

    public void setFirstName (String firstName){
    this.firstName = firstName;
    }

    public String getSecondName(){
        return secondName;
    }

    public void setSecondName (String secondName){
        this.secondName = secondName;
    }
}

public static void main (String [] args){
    Name n = new Name ("Joe", "");
    name.setLastName("Bloggs");
    System.out.println("Name: " + n.getFirstName() + " "         + n.getLasName());
}

So here we have a Java class that takes two parameters and holds two variables. There are also getter & setter methods for both variables. This is quite a lot of code for very little function, so in Scala we:

SCALA
class Name(var firstName:String, var lastName:String)

val n = new Name("Joe", "")

n.lastName = "Bloggs"

println("Name: " + n.firstName + " " + n.lastName)

So these two code snippets do exactly the same thing! That is a demonstration of how Scala can be used to write simple, clean, & elegant code.

This is only a very brief example of why Scala is a very possible alternative to Java or addition to Java (you can use Java & Scala code in the same project). However for a much more in depth look at Scala & a decent tutorial to start you off I would visit Daniel Spiewak’s Scala for Java Refugees. This is where I have taken these code snippets from, and where I learnt the basics of Scala.