scala中带main()的对象和扩展应用程序之间的差异
我正在处理ScalaInAction(这本书仍然是一本MEAP,但代码在github上是公开的) 现在我在第2章中讨论这个restClient:: 首先,我使用scala扩展设置intelliJ,并使用scala中带main()的对象和扩展应用程序之间的差异,scala,Scala,我正在处理ScalaInAction(这本书仍然是一本MEAP,但代码在github上是公开的) 现在我在第2章中讨论这个restClient:: 首先,我使用scala扩展设置intelliJ,并使用main()创建HelloWorld: 我可以通过移动以下行来解决此问题,直到与def相关的顺序正确为止 require( args.size >= 2, "You need at least two arguments to make a get, post, or delete requ
main()创建HelloWorld
:
我可以通过移动以下行来解决此问题,直到与def
相关的顺序正确为止
require( args.size >= 2, "You need at least two arguments to make a get, post, or delete request")
val command = args.head
val params = parseArgs(args)
val url = args.last
command match {
case "post" => handlePostRequest
case "get" => handleGetRequest
case "delete" => handleDeleteRequest
case "options" => handleOptionsRequest
}
在浏览github页面时,我发现:
它使用extends App
而不是main()
方法实现RestClient.scala:
<All the imports>
object RestClient extends App {
<All the rest of the code from RestClient.scala>
}
对象RestClient扩展应用程序{
}
然后,我将我的对象HelloWorld
更改为只使用extends-App
,而不是实现main()
方法,它可以正常工作
为什么执行此操作的main()
方法会产生错误,而扩展应用程序却不会产生错误 因为main()是一个方法,而方法中的变量不能是正向引用
例如:
object Test {
// x, y is object's instance variable, it could be forward referenced
def sum = x + y // This is ok
val y = 10
val x = 10
}
但方法中的代码无法转发引用
object Test {
def sum = {
val t = x + y // This is not ok, you don't have x, y at this point
val x = 10
val y = 20
val z = x + y // This is ok
}
}
在您的情况下,如果将所有代码从RestClient.scala复制粘贴到main(),您将遇到相同的问题,因为var url
是在handlePostRequest中使用后声明的。@om nom nom nom虽然这是标题的副本,但不是所述问题的副本:(@pst好吧,答案提到了这是理解显示行为的关键。@om nom nom我仍然不明白,你能解释一下为什么延迟init解决了错误,但是main()
不是吗?我想说它是的副本。延迟初始化不是问题所在here@sschaef啊,谢谢,我想这就清楚了。为了确保我正确理解这一点,main()方法版本正在按顺序执行main()
的指令而val
直到方法结束时才声明,因此较早的def
s会导致forward references
错误。但是在extends App
使用中,声明和构造被拆分,因此val
s在def
s之前声明,一切都很好。
object Test {
// x, y is object's instance variable, it could be forward referenced
def sum = x + y // This is ok
val y = 10
val x = 10
}
object Test {
def sum = {
val t = x + y // This is not ok, you don't have x, y at this point
val x = 10
val y = 20
val z = x + y // This is ok
}
}