Hello World in Scala for Java Developers

The standard Hello, World in Scala is very simple, as you’d expect. It has a slight twist for Java Developers.

First thing to do is to get an IDE – as a fan of eclipse I choose to use the Scala IDE for Eclipse which I download from here – http://scala-ide.org/download/sdk.html

I’m using one for Mac OS X and based on Luna 4.4.2.

Step 1 – Create a new Scala Project.
Right-click in the left pane and choose ‘New Scala Project’. Call it HelloWorld.

Step 2 – Create a class that extends App
Expand the project by clicking the arrow next to its name.
Right-click on ‘src’ and choose ‘New Scala Class’
In the dialog give it a name of Tutorial and press Finish.

Screen Shot 2015-05-19 at 06.34.07

You now have a class that looks like this:

class Tutorial {

}

Step 3 – Adding the ‘main’ functionality
In Scala we can manually create a main method… but don’t have to.

Scala has traits which are a bit like interfaces and super classes. There is one called App which we can extend and, if we do, the contents of our class becomes runnable.

First, change class to ‘object’

object Tutorial {

}

Now add the trait ‘App’

object Tutorial extends App {

}

Step 4 – Hello, World

And finally add ‘Hello, World.’ The println method is a Scala shortcut for ‘System.out.println’

object Tutorial extends App {
  
  println("Hello, World")
  
}

Step 5 – Run it. In my IDE it’s Run > Run as > Scala Application.

Screen Shot 2015-05-19 at 06.46.28

You should now have the words ‘Hello, World’ in the console at the bottom.

And finally…
If you’d rather have a main method you can always create one:

object Tutorial {

  def main(args: Array[String]) {
    println("Hello, World.")
  }

}
Advertisements