scala 为什么“hello, world”没有输出到控制台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3332751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:19:02  来源:igfitidea点击:

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

scala

提问by Freewind

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

我只是在学习 Scala,我写了这样的“hello,world”程序:

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

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

我将它保存到一个名为“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".

再次运行,它会输出“hello,world”。

采纳答案by Nikolaus Gradwohl

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

如果您想将代码作为脚本运行(通过使用 scala helloworld.scala),您必须通过添加以下行来告诉 scala 您的主要方法所在的位置

  HelloWorld.main(args)

to your code

到你的代码

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

您拥有的第二个选项是使用编译脚本scalac helloworld.scala,然后使用调用类的编译版本scala HelloWorld

回答by michael.kebe

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

就像在 Java 中一样,您应该有一个main-method 作为应用程序的起点。这需要用scalac. 之后编译的类文件可以启动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 scalacommand. Then the content of that file will be wrapped automagically in a main-method.

如果你只有一个小脚本,你可以直接将代码写入文件并使用scala命令运行它。然后该文件的内容将自动包装在main- 方法中。

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

无论如何,我会建议编译和运行。有些事情在“Scalascript”中是不可能的,我现在不记得了。