对象与main()之间的区别和扩展应用程序在scala中

时间:2013-01-27 23:18:39

标签: scala

我正在通过ScalaInAction工作(本书仍然是MEAP,但代码在github上公开) 现在我在第2章看着这个restClient :: https://github.com/nraychaudhuri/scalainaction/blob/master/chap02/RestClient.scala

首先,我使用scala扩展设置了intelliJ,并使用main()创建了一个HelloWorld:

<ALL the imports>

object HelloWorld {
   def main(args: Array[String]) {
     <ALL the rest code from RestClient.scala>
   }
}

编译时出现以下错误:

scala: forward reference extends over defintion of value command
val httppost = new HttpPost(url)
                ^

我可以通过移动以下几行来解决此问题,直到与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页面时,我发现了这个:https://github.com/nraychaudhuri/scalainaction/tree/master/chap02/restclient

使用extends App而不是main()方法实现RestClient.scala:

<All the imports>
object RestClient extends App {
   <All the rest of the code from RestClient.scala>
}

然后我将object HelloWorld更改为仅使用extends App而不是实施main()方法,并且无误地运行

为什么main()方法执行此操作会生成错误,但extends App却没有?

1 个答案:

答案 0 :(得分:5)

因为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中使用后会被声明。