2

Take this snippet of code. This used to be a case class, but I split the class and the object to give the object more methods:

package graphs

class City(val x: Int, val y: Int) {
  def dist(other: City): Double = {
    val xdist  = x - other.x
    val ydist  = y - other.y
    floor(sqrt(xdist * xdist + ydist * ydist) + 0.5)
  }
}

object City {
//  def apply ( x: Int,  y: Int) = new City(x, y)
  def apply = new City(_, _)
}

The way I always understood it is that the apply method written in shorthand would be fully equivalent to the one commented out and scala console seems to agree with me:

scala> graphs.City.apply
res1: (Int, Int) => graphs.City = <function2>

There is, however a problem when using the method:

scala> graphs.City.apply(1,2)
res4: graphs.City = graphs.City@400ff745

scala> graphs.City(1,2)
<console>:8: error: graphs.City.type does not take parameters
              graphs.City(1,2)

The error is exactly the same when I write it in Eclipse. If I switch the method definition to the one commented out (the longer one), there is no such problem.

Is it some desired behavior I didn't know about or a bug that should be reported? I am using Scala 2.10.1.

nietaki
  • 8,758
  • 2
  • 45
  • 56

1 Answers1

3

It is not the same and so tells you the REPL. The commented out version is a method, that takes two params and returns an instance of City. The second version takes no params and returns a function of type (Int,Int) => City. The two are completely different.

drexin
  • 24,225
  • 4
  • 67
  • 81
  • As it turns out those in fact aren't the same, even though "Most of the time we can ignore this distinction". Actual explanations [here](http://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala) – nietaki Jun 12 '13 at 21:31