Thursday, June 5, 2008

first look at scala

recently people are talking a lot about scala ('the next java'). so i decided to have a look at it. in this post i am not going to give an introduction to scala, but i will give some examples of the language features that show what scala can do for you. the examples are taken from the scala tutorial, which is available at

scala runs on the jvm and the syntax should be quite familiar to java developers. hello world in scala looks like this:

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

there are some interesting things about this. first, the object declaration means that HelloWorld is a singleton object. that is also why the main 'method' is not declared static. as HelloWorld is a singleton main is 'globally available' and doesn't need to be static. static members (methods) or fields do not exist in scala. second, main doesn't declare a return type. it's called a procedure method.

as said, scala runs on the jvm. because of that scala classes can interact with existing java classes. for example you can import and use java classes:

import java.util.{Date, Locale}
import java.text.DateFormat
import java.text.DateFormat._

these import statements show that you can import multiple classes from one packge with that curly braces notation. and you can import all names from a package or class with the underscore notation. the above import makes members of DateFormat available, so you can call the static method getDateInstance() directly. Why not use the * notation for the imports? * is a valid identifier in scala. you'll see why, soon.

Methods with a single argument can be called in infix syntax in scala that means the method format of DateFormat can be called like in the following example:

val now = new Date
val df = getDateInstance()
val str = df format now

this call is equivalent to df.format(now). at the first look this is not quite an interesting feature but it offers some possibilities, one of which i'll show next. in scala 'everything is an object', e.g. primitive types as well. then remember that * is a valid identifier and the infix
syntax for methods. then look at this code and try to figure out how it works:

2 + 3 * 4 / 2

this is equivalent to


all the integers are objects and the operators are methods of these objects. operators are method calls.

this was my first look at scala. more looks coming soon, for sure ...

No comments: