Scala: Hello World!

Nowadays, there are many languages running on the Java Virtual Machine, but in the beginning, the JVM could run only compiled Java programs, now we have plenty full of new languages, some of them designed expressly for the JVM, others that had a version capable of running on it.

People is wondering which will be the Next Big JVM Language. There are many candidates who fight for being the chosen one. Scala, JRuby, Jython, Groovy, Clojure are among them.

Recently, a great book came to my hands, Programming in Scala. A comprehensive step-by-step guide, it’s co-authored by Martin Odersky, Lex Spoon and Bill Venners. Mr. Odersky is the creator of the Scala language and also the co-designer of Java generics. In this post, a Hello World example in Scala will be made.

The very first thing to do is download the Scala distribution, you can find it here. The last stable release is 2.8.0. Now the Scala interpreter is installed in our system. With this interpreter, our first Scala program can be done and executed.

Scala is an Object Oriented and a functional programming language. It can be executed within a Java code and vice versa. The semicolon at the end of each instruction is optional, so you don’t have to put it at the end of every sentence. It is less verbose than Java, thus some type declarations can be omitted. For instance, you can say:

var x = new HashMap[int, String]()

Instead of:

var x Map[int, String]() = new HashMap[int, String]()

These are only a few characteristics of Scala. Now,let’s continue with some glossary:

  • val: It’s a variable that could not be modified, it’s like a final variable in Java. Once assigned, it can’t be reassigned
  • var: It’s a variable, it can be modified
  • def: It defines a function
  • print and println: prints the passed the String to the standard output. It’s similar to System.out.println in Java
  • while: the instruction for loops
  • if: the instruction for deciding
  • (paramName1 : Type, paramName2 : Type => paramName1 + paramName2): also is the format of literal functions.
  • foreach (element => action) : the instruction for iterations
  • for (element <- elements): another instruction for iterations, element is a val not a var

Let’s put it all together. The first example is a simple Hello World!. Put the following code into a file named hello.scala

println(“Hello World!”)

Then from the OS prompt, execute:

$> scala hello.scala

The result will be:

Hello World!

Let’s make a more sophisticated sample. Definition of factorial function and execution with the first number typed in the standard input.

def factorial ( x : Int ) : Int = { if ( x == 0 ) 1 else x * factorial ( x - 1 ) } println(factorial(args(0).toInt))

And yet, another example. Capitalize the words typed in the standard input.

args.foreach(arg => print(arg.capitalize))

Executing this:

$> scala capitalize.scala hello world !

The output will be: