Difference between object with main () and application extension in scala

I'm working through ScalaInAction (the book is still MEAP, but the code is open to github) I'm in chapter 2 now looking at this restClient :: https://github.com/nraychaudhuri/scalainaction/blob/master/chap02/RestClient.scala

I first set up intelliJ with scala extensions and created HelloWorld with main()

:

<ALL the imports>

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

      

I am getting the following error when compiling:

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

      

I can fix this by moving the next lines around until the ordering is correct with respect to def

's

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
}

      

While browsing through the github page, I found this: https://github.com/nraychaudhuri/scalainaction/tree/master/chap02/restclient

Used to use RestClient.scala using extends App

instead of method main()

:

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

      

Then I changed mine object HelloWorld

to just use extends App

the method instead of implementing main()

and it works without error

Why main()

does the method method throw an error for this but extends App

not?

+3


source to share


1 answer


Because main () is a method, and a variable in a method cannot be a direct reference.

For example:

object Test {

   // x, y is object instance variable, it could be forward referenced

   def sum = x + y // This is ok
   val y = 10    
   val x = 10

}

      



But the code in the method cannot be redirected.

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
    }
}

      

In your case, if you copy all the codes from RestClient.scala to main (), you have the same problem because it is var url

declared after using it in handlePostRequest.

+5


source







All Articles