且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

scala 脚本和应用程序的区别

更新时间:2023-10-16 22:32:52

我觉得作者的意思是一个普通的scala文件需要定义一个类或者一个对象才能工作/有用,你不能使用***表达式(因为编译文件的入口点是预定义的).例如:

I think that what the author means is that a regular scala file needs to define a class or an object in order to work/be useful, you can't use top-level expressions (because the entry-points to a compiled file are pre-defined). For example:

println("foo")

object Bar {
    // Some code
}

println 语句在 .scala 文件的顶层无效,因为唯一的逻辑解释是在编译时运行它,这不会这真的很有意义.

The println statement is invalid in the top-level of a .scala file, because the only logical interpretation would be to run it at compile time, which doesn't really make sense.

相比之下,Scala 脚本可以在顶层包含表达式,因为这些是在脚本运行时执行的,这又是有意义的.另一方面,如果 Scala 脚本文件只包含定义,它也将毫无用处,因为脚本不知道如何处理定义.但是,如果您以某种方式使用这些定义,那就没问题了,例如:

Scala scripts in contrast can contain expressions on the top-level, because those are executed when the script is run, which makes sense again. If a Scala script file only contains definitions on the other hand, it would be useless as well, because the script wouldn't know what to do with the definitions. If you'd use the definitions in some way, however, that'd be okay again, e.g.:

object Foo {
    def bar = "test"
}

println(Foo.bar)

后者作为 scala 脚本是有效的,因为最后一个语句是使用前一个定义的表达式,而不是定义本身.

The latter is valid as a scala script, because the last statement is an expression using the previous definition, but not a definition itself.