3

私は ScalaInAction に取り組んでいます (本はまだ MEAP ですが、コードは github で公開されています) 現在、この restClient を見ている第 2 章にいます: : https://github.com/nraychaudhuri/scalainaction/blob/master/ chap02/RestClient.scala

まず、scala 拡張機能を使用して intelliJ をセットアップし、次のように HelloWorld を作成しましたmain()

<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メソッドの代わりにRestClient.scala を使用して実装するmain()もの:

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

次に、メソッドを実装する代わりにobject HelloWorld使用するように変更しましたが、エラーなしで動作しますextends Appmain()

main()これを行う方法でエラーが発生するのに、エラーが発生しないのはなぜextends Appですか?

4

1 に答える 1

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 での使用後に宣言されるため、同じ問題が発生します。

于 2013-01-28T09:32:33.273 に答える