Sunday, 25 December 2011

Scala Hello World

You are probably wondering how to write the first scala program. Let’s start with the simple application, which calculates the area of a square.

Runnable application

In order to create runnable application we need to define a singleton object containing a main method. Let’s call it Area. (We’ll talk about singleton objects later.)
package helloWorld
object Area{
  def main(args: Array[String]){
    var width = args(0).toDouble
    println("Area = " + width * width ) 
  }
}

Methods

Method definition always starts with the def keyword followed by method name and comma-separated list of parameters. Unlike in java, parameter name comes first, and is followed by the colon and the parameter type, i.e.
def main(args: Array[String]){ 
  ... 
}
Method main takes one parameter called args of type Array[String].

Scala has no primitive array type

Array[String] is a class similar to ArrayList in java. There is no concept of primitive array in scala.

Generic types use square brackets

Array[String] is just an Array class parameterized by the String type.

Variables

var width = args(0).toDouble
To declare a variable we need to use var keyword. Scala compiler infers (guesses) a type of the variable. In our example, scala figures out that width is a Double. If you want you can be explicit about the types:
var width : Double = args(0).toDouble

Random access with () operator

You probably noticed that we are accessing elements of the args class with () operator. Array implements a special method apply, which allows random access to its elements using () operator, i.e. args(0)

Predef

You might wonder where does the println come from. It is defined in the Predef singleton object and is automatically imported in every scala file.

No semicolons

Semicolons at the end of the line are optional.

Compiling and running scala program

To run scala program you will need a scala distribution. You can download it from www.scala-lang.org. You also need JDK (Java Development Kit). Then make sure that scalac and scala are on the path and run the following commands:
> mkdir out
> scalac Area.scala -d out
> scala -cp out helloWorld.Area 5
Area = 25.0

Scalac is similar to javac; it compiles our file Area.scala into out directory. Then we run scala virtual machine, which is nothing more than java virtual machine with scala standard library on the classpath.


Enjoy!

No comments:

Post a Comment