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".
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With