Getting start with Scala

In this post we will introduce Scala programming language. Also we will learn how to install it and create a famous Hello World application.

Scala as it’s own site says, is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothy integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive.

The name Scala stands for “scalable language”. You can use Scala to a wide range of programing tasks, from writing small scripts to building large systems.

Scala runs on the standard Java platform and interoperates seamlessly with all Java libraries.

Technically, Scala is a blend of object-oriented and functional programing concepts in a statically typed language.

Scala is expressive & light-weight

var capitals = Map (
  "Brazil" -> "Brasilia",
  "US" -> "Washington",
  "France" -> "Paris"
)
capitals += ("Japan" -> "Tokio")
println(capital("Brazil"))

Everything is an object

Scala is a pure object-oriented language in the sense that everything is an object, including numbers or functions.

Numbers are objects

Since numbers are objects, they also have methods. And in fact, an arithmetic operations + – * / consists exclusively of method calls.

This expression:

1 + 2 * 3 / x

Is equivalent to the following:

(1).+(((2).*(3))./(x))

Functions are objects

Functions are also object in Scala. It’s possible to pass functions as arguments, to store them in variables, and return them from other functions. This ability to manipulate functions as values is one of the cornerstone of a very interesting programming paradigm called functional programming.

See the code example:

object Timer {
  def oncePerSecond(callback: () => Unit) {
    while (true) { callback(); Thread sleep 1000 }
  }
  def timeFlies() {
    println("time flies like an arrow")
  }

  def main(args: Array[String]) {
    oncePerSecond(timeFlies)
  }
}

Classes

Classes in Scala are declared using a syntax which is close to Javaś syntax. One important different is that classes in Scala can have parameters:

class Complex(real: Double, imaginary: Double) {
  def re() = real
  def im() = imaginary
}

This class takes two arguments. These arguments must be passed when creating an instanceof class Complex, as follow: new Complex(1.5, 2.3). Also the class contains two methods, called re and im, which give access to these two parts.

Inheritance and overriding

All classes in Scala inherit from a super-class. Whem no super-class is specified, scala.AnyRef is implicity used.

It is possible to override methods inherited from a super-class. It is however mandatory to explicity specify that a method overrides another one using the override modified:

class Complex(real: Double, imaginary: Double) {
  def re = real
  def im = imaginary

  override def toString() =
    "" + re + (if (im < 0) "" else "+") + im + "i"
}

Traits

Apart from inheriting code from a super-class, a Scala class can also import code from one or server traits.

The easiest wary to understand what traits are is to view them as interfaces which can also contains code. When a class inherits froma trait, it implements the trait’s interface, and inherits all the code contained in the trait.

Let’s look a classical example: ordered object. It is often useful to be able to compare objects of a given class among themselves, for example to sort them. In Java, object which are comparable implement the Comparable interface. In Scala, we can do a bit better by defining our equivalent of Comparable as a trait:

trait Ord {
  def <  (that: Any): Boolean
  def <= (that: Any): Boolean = (this < that) || (this == that)
  def >  (that: Any): Boolean = !(this <= that)
  def >= (that: Any): Boolean = !(this < that)
}

The type Any which is used above is the type which is a super-type of all other types in Scala.

Let’s define a Date class representing date:

class Date(y: Int, m: Int, d: Int) extends Ord {
  def year = y
  def month = m
  def day = d

  override def toString(): String = year + "-" + month + "-" + day

  override def equals(that: Any) : Boolean =
    that.isInstanceOf[Date] && {
      val o = that.asInstanceOf[Date]
      o.day == day && o.month == month && o.year == year
    }

  def < (that: Any): Boolean = {
    if (!that.isInstanceOf[Date])
      error("cannot compare " + that + " and Date")

    val o = that.asInstanceOf[Date]
    (year < o.year) ||
    (year == o.year && (month < o.month ||
                        month == o.month && day < o.day)))
  }
}

The last method to define is the predicate which tests for inferiority. It makes use of a predefined method, error, which throws an exception with the given error message.

Installing Scala

To install Scala is pretty simple. First you need to download Scala from http://www.scala-lang.org/downloads.

Then unpack the Scala installation file and set the environment variables:

Environment Variable Value
Unix $SCALA_HOME
$PATH
usr/local/share/scala
$PATH:$SCALA_HOME/bin
Windows %SCALA_HOME%
%PATH%
c:\Progra~1\Scala
%PATH%;%SCALA_HOME%\bin

Run it interactively

The scala command starts an interactive shell where Scala expressions are interpreted interactively.

> scala
  This is a Scala shell.
  Type in expressions to have them evaluated.
  Type :help for more information.

  scala> object HelloWorld {
       |   def main(args: Array[String]) {
       |     println("Hello, world!")
       |   }
       | }
  defined module HelloWorld

  scala> HelloWorld.main(null)
  Hello, world!
  unnamed0: Unit = ()
  scala>:q

Compile it

The scalac command compiles Scala source files and generates Java bytecode which can be executed on any standart JVM

> scalac HelloWorld.scala

Execute it

The scala command executes the generated bytecode with the appropriate options:

> scala -classpath . HelloWorld

The Hello World Program

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello World!")
  }
}

If the object extends Application, then all the statements contained in that object will be executed, so we don’t need a main method:

object HelloWorld extends Application {
  println("Hello World")
}

Here is another HelloWorld example in Scala:

object HelloWorld extends Application {
  for(i<-List("olleH", " ", "!dlrow")) {
    print(i.reverse)
  }
}

I intend to write more about Scala here, but if you want to lean more right now go to Scala site: http://www.scala-lang.org.

That’s all folks!

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: