• Home
  • Portfolio
  • Products
    • HandyBirthdays
    • BashSupport for IntelliJ®
  • Scala Newsletter
    • [Issue 1] Boxing / unboxing in Scala
    • [Issue 2] Scala 101: Introduction
  • References
  • Contact
Joachim Ansorg IT-Services
Diese Seite in Deutsch

Scala 101: Introduction

by Joachim Ansorg (2009-04-16)

Abstract

The programming language is introduced. Using examples an overview of the most important language features is given.

The programming language "Scala"

A warm welcome to the 2nd issue of the Scala Newsletter. This is the first part of the Scala 101, an introduction to the programming language Scala.

Scala is a scalable programming language which nicely integrates into the Java world. The following sections will give you an overview about the most important concepts. Detailed explanations will be made available in the next issues of the Scala 101 series.

Where does Scala come from?

Scala is being developed at the University of Lausanne. Martin Odersky, a German, is responsible for the continued development.

Sample code

To introduce Scala we will show small examples of code. A very short, albeit complete program is the typical "Hello World":

Example 1. "Hello World" in Scala
package scala101_001

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

Scala - short and crisp

Scala is characterized by several features:

  • integrated. Scala code can be executed in the Java VM. Existing Java source code can be used with Scala. Instead of reinventing the wheel Scala bases on established technologies.

  • Object oriented. Scala is a object oriented programming language. But the possibilities goes beyond what Java offers.

  • Functional and imperativ. Scala combines aspects of functional and imperative programming languages. The programmer can choose between the two depending on his current needs

  • Concise. Typical Scala source code is shorter than the homologous Java code. This means less writing and reading for the programmer. If necessary it's possible to write more verbose source code, for example in complex parts of aprogram.

  • Customizable. Scalas syntax has been developed to allow easy customisations which nicely integrate into the language. It's possible to create constructs which are similair to the language's keywords. Scala is very suitable for the development of domain specific languages (DSLs).

What does characterise Scala?

Syntax

On the one hand Scala's syntax is terse, on the other hand it's powerful. In comparision with Java less source code has to be written to express the same idea.

Example 2. Output of the primes between 1 and 100
object SyntaxDemo {
  def isPrime(n: Int) = (1 to n).toList.count(n % _ == 0) == 2

  def main(args: Array[String]): Unit =
        (1 to 100).filter(isPrime).foreach(println)
}
[Note]Note
Of course, there are far better methods to find primes than this naive implementation. The example's purpose is to show that it's possible to write easy to understand and in comparision with Java shorter source code.

Scala is a type safe language. This means that It's necessary to write down types for variables, parameters, etc. Often this information is redundant, though. In Scala you only need to write down the really necessary type information, Scala is infering the left out parts for you. This feature is called type inference.

Example 3. Scala's type inference
val v = "Hey, Scala knows that I'm a String"
println(v) 

If you wish you can write down the optional type information. In complicated parts of a program this helps to improve the readability. Besides it can help the compiler to infer the types of complicated expressions.

Example 4. Specification of the optional type
val v : String = "Hey, Scala knows that I'm a String"
println(v) 

Classes, Modules and Traits

In Java there are classes and interfaces. In Scala there are classes, modules and traits.

  • Classes. Scala's classes are very similair to Java's classes. But there are not static methods allowed, for example.

  • Modules. Modules in Scala are similair to the design pattern "Singleton". Scalas concept of modules is sometimes also called Singleton object. Modules are marked by the keyword object. At runtime there's always only one instance of a certain module.

  • Traits. In Java there's nothing which resembles the concept of traits. Traits enable the software developer to combine several independant building blocks to another thing, e.g. a class or module.

case class

The so called "case class" is a simplification of a certain use case of classes. Often classes with read-only access to certain information are needed which offer additional operations to work with the data.

Example 5. Java class
public class JavaPerson{
    private final String firstname;
    private final String lastname;

    public JavaPerson(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public String getFirstname() {
        return firstname;
    }

    public String getLastname() {
        return lastname;
    }
} 

The Java class above can be replaces by a simple case class. The following case class has the same functionality as the example above:

Example 6. Equivalent Scala case class
case class ScalaPerson(firstname:String, lastname:String)
                        

Functions and closures

In functional languages functions play a central role. In imperative languages like Java data takes this role. Scala interweaves both worlds to one.

Scala allows to reference functions. For example it's possible to hand functions over to other functions as parameter. Anonymous functions are possible, as well. The following example demonstrates the use of functions in Scala:

Example 7. Functions in Scala
object FoodDemo {
  val food = "Bananas" :: "Bred" :: "Orange juice" :: Nil

  def main(args:Array[String]) = {
    food.foreach(thing => println("Please buy " + thing))
  }
}
                        

The construct thing => println("Please buy " + thing) isa (anonymous) function, which is applied to every element of the list food. The output of the program is:

Please buy Bananas
Please buy Bred
Please buy Orange juice
                    

Actors

Scala's standard library offers an elegant concept of parallel programming. Messages are exchanged between several actors / participants. The messages of each participant are collected and worked on one after another. Two actors can work in parallel on their messages.

It's interesting that usually locks are not needed. This reduces the vulnerability to failures. And it eases the development of event driven applications.

Example 8. A simple Scala actor
case class Add(n:Int)
case class Substract(n:Int)
case class Print()
case class Shutdown()

class CalculatingActor extends Actor {
  import Actor._

  var result : Int = 0

  def act() = loop{
    react{
      case Add(n:Int) => result = result + n
      case Substract(n:Int) =>  result = result - n
      case Print() => println(result)
      case Shutdown() => exit()
    }
  }
} 

This simple actor shows how Scala's concept of actors can help to develop asynchronous, message based systems. In the example add and substraction tasks are submitted and calculated asynchronously.

Further information

Web sites

The following web sites contain important information about Scala and related topics.

  • Scala web pages. The web pages of the Scala project contain loads of information about many aspects of the language.On the page Documentation most of the documents are referenced.
    www.scala-lang.org

  • IBM's The busy Java developer's guide to Scala. IBM's developerWorks contains the series "The busy Java developer's guide to Scala". The authors explain different aspects of software development with Scala.
    IBM's The busy Java developer's guide to Scala

  • Lift. Lift is a very elegant framework for the development of moden internet applications.
    Lift - The Scala web framework.

Books

This is a list of the books which are about Scala. Some of them are still under development but will be available soon.

  • Programming in Scala. Martin Odersky, the father of Scala, is a co-author of this book. Accordingly the book is deep and detailed. It's worth reading despite of the more than 700 pages. But it's not appropiate for newbies or for a quick introduction to the language. It's highly recommendable for detailed reading and as a refernce.
    It's available as a print edition and as an eBook.The Book's website

  • Programming Scala: Tackle Multi-Core Complexity on the Java Virtual Machine. The book is set to e released in may 2009 and obviously takes a closer look at the development of multi core applications. We still have to see if it fulfils it's promises.
    The book's website.

  • Beginning Scala. Beginning Scala is another book about Scala which is still in development. The author is David Pollak, known for this outstanding web framework Lift. In my opinion this is going to be a high-quality and easy to read book.
    The book's website

Subscribe for free

Subscribe - you will receive all new issues of the Scala newsletter by email. For free!

Abstract

The programming language is introduced. Using examples an overview of the most important language features is given.

Table of Contents

The programming language "Scala"
Where does Scala come from?
Sample code
Scala - short and crisp
What does characterise Scala?
Syntax
Classes, Modules and Traits
case class
Functions and closures
Actors
Further information
Web sites
Books

List of Examples

1. "Hello World" in Scala
2. Output of the primes between 1 and 100
3. Scala's type inference
4. Specification of the optional type
5. Java class
6. Equivalent Scala case class
7. Functions in Scala
8. A simple Scala actor
  • Copyright © 2009, 2010 Joachim Ansorg IT-Services. All rights reserved.
  • Imprint