Quick start Scala from Java

From Java to Scala - Syntax

This presentation is a guide to jump start Scala development starting from a Java background. Here we focus on the syntax differences between Java and Scala.

You should already know Java

Of course here Java knowledge is taken for granted. As a consequence, unless you already know Java, you may not be able to understand this presentation.

Code samples are Scala, unless specified otherwise.

You should assume all the code in the samples is Scala code, unless stated otherwise.

Java code is marked with a comment

Since we will compare, some Java code will be provided. If it is Java, then a comment will state it.

Declarations

Let’s start our journey looking at declarations.

Variables

First step is learning how to declare variables and constants.

Methods

Afterwards, we will see how to declare methods, that generally belongs to a class.

Classes

Finally we will examine how classes are declared in Scala.

Variables

1
2
3
// Java
int x = 1;
final String x = "hello";

Let’s start with variables. Here I am declaring first an integer variable in Java, second a String constant.

1
2
// In Scala note the "var" for variables
var x : Int = 1

Here is the equivalent Scala declaration of an integer variable. As you can see, the most important difference I placed the type after the variable, separated by a colon. Note I have to precede a variable declaration with the var keyword.

1
2
// Also in Scala we use "val" for constants
val y : String = "hello"

Likewise, if you want a constant, you have use instead the keyword val. This code is declaring a String constant initialized with the given value. Note how I am using the val keyword to declare I cannot modify the value anymore.

Type Inference

The Scala code we wrote looks longer than the equivalent Java code. Scala, however, most of the time allows omitting the type declaration. The compiler can deduct the type of the variable automatically.

1
2
// using type inference, type is integer
var x = 1

Using the type inference, you can omit the type declaration. The compiler, just seeing the integer one, can decide the variable type is actually integer.

1
2
// using type inference, type is string
val y = "hello"

The same holds true for the second example. Here we are instead a constant of type String. The type is deducted from the string constant.

Scala has semicolon inference!

You may have noticed in Scala code there is not a semicolon at the every declaration. Indeed semicolons are not required because Scala can infer it from the source code.

End-of-line ends complete statements

1
2
3
// here end-of-line ends the statement
val a = 1 + 2
val b = a + 1

In the simplest case, an end line ends statements… but only if they are complete statements! This is important.

End-of-line does not end incomplete statements

1
2
3
4
// here end-of-line DOES NOT end the statement
val a = 1 +
2
val b = a + 1

However, as you can see in this example, a dangling plus does not end the statement. Scala infers the statement is not complete, so it looks at the next line for the rest. This feature is actually pretty handy for splitting long statements over multiple lines.

Parametric Types

1
2
3
// Java
import java.util.ArrayList;
ArrayList<String> ls = new ArrayList<String>()

Let’s see now how parametric types are managed. We start with a classical list parametrized to contains only Strings.

1
2
3
4
// equivalent Scala code
import scala.collection.mutable.ArrayBuffer
val ls: ArrayBuffer[String]
= new ArrayBuffer[String]()

You can write equivalent Scala code just replacing the angle brackets with square brakets. Of course we have also to apply the changes we already discussed and use an appropriate class.

1
2
// simplified Scala code
val ls = new ArrayBuffer[String]()

Here is how we can write the declaration using type inference.

Methods

1
2
// Java
public int sum(x: Int, y: Int) { return x + y; }

Now it is the turn of examinating methods. Here you can see a simple Java method declaration. It is named sum, it takes two integers and of course it returns the sum.

Use def to declare a method

1
def sum(x: Int, y: Int) : Int = { return x + y }

Here is the Scala version. The first difference you may notice is you need the keyword def to precede the method name.

method type follows the parameters, separated by a “:

As we did for variables, the parameter type follows the parameter name in the parameter list. Also the method type follows the parameter list, separated by a colon.

you need an “=“ before the body

Note the function body is separated from the declaration by an equal sign.

public by default

Finally, you do not need to say the method is public. Indeed, public is the default visibility, so it does not need to be explicit defined

Let’s simplify

1
2
3
def sum(x: Int, y: Int) : Int = { return x + y }
// can be written
def sum(x: Int, y: Int) = x + y

The initial can actually be simplified a lot using Scala rules.

you do not need a return

You do not need to specify a return statement. The returned value is simply the value of the latest expression.

function type is inferred

Generally (but not always) we do not need to specify the type of the method. It is is inferred from the type of the latest expression.

braces not required for a single expression

Finally, when the body is a simple expression, braces around the expression are not required.

parameter types cannot be inferred

Note we do need to specify the type of the parameters. Type inference cannot decide the types of the parameters you want. It is your decision what the function need to receive in input.

Procedures

1
2
// Java
public void hello() {System.out.println("hello");}

A special case occurs when a method does not return any value. We say then it is a procedure.

1
2
// is Scala we use Unit when  we do not want to return any value
def hello(): Unit = { println("hello") }

A Java void type translates in a Scala Unit. Actually a Unit is an empty tuple, as we will see later. We use this value as the return value when there is not any result.

it can be simplified too

1
def hello() { println("Hello") }

Also this code can be shortened. I can declare that a function is returning a Unit just omitting the equal sign. In this case however braces cannot be omitted.

Classes

Now we can consider some more complicated examples, related to classes.

1
2
3
4
5
6
7
// Java
public class Person {
public String name;
public Person(String firstname, String surname) {
this.name = name+" "+surname;
}
}

Here is a simple java class, with a single field, name. Note the name is actually calculated concatating the first name and the surname. There is a constructor which receive two parameters and produce the actual value of the field.

1
2
3
4
5
// A class declaration in Scala
class Person(firstname: String, surname: String) {
var name = firstname // a declaration
name = name + " " + surname // a statement
}

Here is the equivalent Scala code. As you can see, the declaration of a class in Scala looks like just the declaration of its constructor. The code looks like a procedure, but you use class instead of def. Note the body of the class can contain generic statements, not just declarations. In Java you can only have declarations.

A class constructor requires a new

1
2
val a = new Person("Mickey", "Mouse")
println(a.name)

Mickey Mouse

A class constructor must be executed prefixed by the new keyword, as in Java. All the variables created in the body are persistent and available as fields.

Classes with initializer

1
2
3
4
5
6
public class Point { // Java
public int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
} }

Here is a common idiom in Java. We create a class with 2 fields, and we initialize them with parameters with the same name.

1
2
3
4
5
6
// It is simpler in Scala
class Point(var x: Int, var y: Int)

val p = new Point(1,2)

println(p.x + p.y)
1
3

In scala this code is simpler: just use the prefix var for each parameter and the parameters become fields without the need of having to copy them.

Classes with read only fields

1
2
3
4
5
6
// Java
class Box {
private int value;
public Box(int value) { this.value = value; }
public getValue() { return value; }
}

Another common idiom in Java is the getter pattern. To create a read only field, you define a private field and a getter to read it. Then you initialize the field with a contructor.

1
2
3
4
// In scala you can declare a readonly field
class Box(val value: Int)
val b = new Box(2)
println(b.value)
1
2

This pattern is much simpler in Scala: just define a parameter as a val. It can then be read but the compiler will refuse to compile code which changes it.