Scala for Java programmers

Scala is one of programming languages created for the Java Virtual Machine. It’s concise, both object-oriented (everything is an object) and  functional language (every function is a value). Allows passing functions (function is an object) as parameters. It is strongly typed with type inferring. And it integrates easily with Java.

Functional languages are gaining more popularity because they bring different paradigm of concurrency. Imperative languages with shared state need extensive synchronization. Evaluation of functions passing immutable objects can be easily distributed. There is nothing to synchronize there.

From a point of view of a Java programmer, Scala can be used as general purpose language offering better productivity. Let’s look at some language features of Scala.

Hello World

object HelloWorld {
  def main(args: Array[String]) {
    System.out.println("Hello, world!")
  }
}

We declared HelloWorld as an singleton object instantiated on first use. Look at the main method. In Scala there are no static methods.

Types

import java.math.BigInteger

val arr = Array(
    "String",
    new BigInt(BigInteger.ONE),
    123,
    true,
    (s : String) => print("Printing: " + s)
  )

for (x

In Scala all values are objects. They inherit from either scala.Any or scala.AnyRef class if they are respectively primitive types or other types. Usually what seams to be an operator is a function call.

Tuples

val tuple = ("TouK", "Bohaterów Września 9", "Warsaw", "Poland")

println(tuple)
println(tuple._1)
println(tuple._2)
println(tuple._3)

val (company, street, town, country) = tuple

println(tuple._1)

Tuples are generic classes whose fields can be accessed using selectors. Selectors are implemented as Product trait. Together with type inferring this is quite powerful language construct.

Functions

def fibonacci(i : BigInt) : BigInt =
  if (i

Every expression yields a value. Missing else expression would yield Unit (void, nothing). Functions can be nested and because they are object can be passed to other functions:

val list = List(1 to 10)
list(0).foreach((i) => println(i))

Conditionals

Conditionals are expressions – see fibonacci function above. They yield a value; missing else statement yields ()scala.Unit. Guard condition should evaluate to boolean.

object HelloWorld {
  def main(args: Array[String]) {
    if (args.isEmpty)
      println("Usage ...")
    else {
      //parse
      //run
    }
  }
}

For loop

for (i

As you can see for loops allows for concise expression of nested loops. Guards filter generated values. Scala comes with do loops and while loops as well.

Pattern Matching

Pattern matching is a language construct not existing in Java. As read in Scala Reference, patterns can be built from: constants, constructors, variables and type tests.

def sumList(xs : List[Int]) : Int =
  xs match
  {
    case List() => 0 //type matching, yield 0
    case head :: tail => head + sumList(tail) //inverse cons operation, list decomposition
  }

val numlist = 1 :: 2 :: 3 :: 4 :: Nil

println(sumList(numlist));

Classes

class Address(val street : String, town : String, zip : String)
{

}

Compiles to:

Compiled from "Address.scala"
public class Address extends java.lang.Object implements scala.ScalaObject{
    private final java.lang.String zip;
    private final java.lang.String town;
    private final java.lang.String street;
    public Address(java.lang.String, java.lang.String, java.lang.String);
    public java.lang.String zip();
    public java.lang.String town();
    public java.lang.String street();
    public int $tag()       throws java.rmi.RemoteException;
}

Scala class template generates: private final fields, constructor and accessor methods. Very similar:

class Address(val street : String, town : String, zip : String)
{

}

Compiles to:

Compiled from "Address.scala"
public class Address extends java.lang.Object implements scala.ScalaObject{
    private java.lang.String zip;
    private java.lang.String town;
    private java.lang.String street;
    public Address(java.lang.String, java.lang.String, java.lang.String);
    public void zip_$eq(java.lang.String);
    public java.lang.String zip();
    public void town_$eq(java.lang.String);
    public java.lang.String town();
    public void street_$eq(java.lang.String);
    public java.lang.String street();
    public int $tag()       throws java.rmi.RemoteException;
}

Which creates mutable object with accessors:

val add = new Address("Bohaterow Wrzesnia 9", "Warsaw", "")
add.zip = "02-389"
println(add.zip)

2 thoughts on “Scala for Java programmers

  1. Nice post!

    It’s also worth noting, that pattern matching can successfully eliminate the need for Visitor pattern. It’s also more general, as one can match not only on the type of the object, but also on it’s fields’ values.

    Scala FTW! :)

Leave a Reply

Your email address will not be published.