scala 脚本和应用程序的区别 [英] The difference between scala script and application

查看:34
本文介绍了scala 脚本和应用程序的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala 脚本和 scala 应用程序有什么区别?请举例

What is the difference between a scala script and scala application? Please provide an example

我正在阅读的这本书说,脚本必须始终以结果表达式结尾,而应用程序必须以定义结尾.不幸的是没有显示清楚的例子.

The book I am reading says that a script must always end in a result expression whereas the application ends in a definition. Unfortunately no clear example is shown.

请帮我澄清一下

推荐答案

我觉得作者的意思是一个普通的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.

这篇关于scala 脚本和应用程序的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆