views:

116

answers:

2

I'm just learning scala, and I wrote the "hello,world" program like this:

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

I saved it to a file named "helloworld.scala"

Now I run it in the console:

scala helloworld.scala

But nothing outputed. I thought it will output "Hello, world". Why?

PS

If I modify the content to:

println("Hello, world")

and run again, it will output "hello,world".

+6  A: 

You have two options.

Compile and Run:

As in Java you should have a main-method as a starting point of you application. This needs to be compiled with scalac. After that the compiled class file can be started with scala ClassName

scalac helloworld.scala
scala HelloWorld

Script:

If you have a small script only, you can directly write code into a file and run it with the scala command. Then the content of that file will be wrapped automagically in a main-method.

// hello.scala, only containing this:
println("Hello, world!")

then run it:

scala hello.scala

Anyway I would recomment to compile and run. There are some things, that are not possible in a "Scalascript", which I do not remember right now.

michael.kebe
When running a compiled Scala program, you sometimes must add "-cp ." to include the current directory so that the .class files could be found: scala -cp . HelloWorld
olle kullberg
+3  A: 

if you want to run your code as a script (by using scala helloworld.scala) you have to tell scala where your main method is by adding the line

  HelloWorld.main(args)

to your code

the second option you have is compiling the script by using scalac helloworld.scala and then calling the compiled version of your class using scala HelloWorld

Nikolaus Gradwohl