Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the "hello, world" is not output to the console?

Tags:

scala

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".

like image 627
Freewind Avatar asked Jul 26 '10 06:07

Freewind


2 Answers

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

like image 80
Nikolaus Gradwohl Avatar answered Sep 22 '22 13:09

Nikolaus Gradwohl


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.

like image 24
michael.kebe Avatar answered Sep 21 '22 13:09

michael.kebe