Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala println not working with App trait

When I use the scala App trait, I can't get println to work.

This simple example prints as expected,

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

But once I introduce the trait it does not,

object HelloWorld extends App {
  println("Hello, world!")
}

I get no errors but nothing prints to the console.

like image 768
James McMahon Avatar asked Jun 22 '12 00:06

James McMahon


2 Answers

Did you compile it first (running scalac HelloWorld.scala)? See this comment: http://www.scala-lang.org/node/9483#comment-40627

Edited to add more explanation: The first version actually was compiled. Scala files without an explicit main method are run uncompiled as scripts. That means that for your second version, the commands in the file are run sequentially, as though they had been entered into the interpreter--so, the object HelloWorld is created, but no method is called on it. There's more information about Scala as a scripting language here (scroll to Step 5): http://www.artima.com/scalazine/articles/steps.html

like image 70
Kelsey Gilmore-Innis Avatar answered Nov 07 '22 04:11

Kelsey Gilmore-Innis


Add a line

object HelloWorld extends App {
  /* code */
}

HelloWorld.main(args)

at the end of your file.

The Class defines the method but it need to be called too.

like image 5
A. Rabus Avatar answered Nov 07 '22 02:11

A. Rabus