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

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

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.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.