O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 34

The Main Thing

One of the many convenient features of Scala is the ability to put initialization statements directly in a class, trait, or object body, rather than having to define an explicit primary constructor:

  class HelloWorld {
    val msg = "Hello World!" 
    println(msg)
  }
    scala> new HelloWorld
  Hello World!

Scala leverages this feature to make it equally easy to define programs that can be run from the command line.[1] Instead of having to define a main method, an object can simply inherit from the App trait. The body of the object then automatically becomes the content of the main method, and is executed when the program is run:

  object HelloWorld extends App {
    println("Hello World!")
  }
    scala> HelloWorld main Array()
  Hello World! ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required