开发者

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

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜