10
votes

In Scala IDE I get the following error about the class I am to compile:

in object MapArea, multiple overloaded alternatives of method addAnim define default arguments.

So yes, They do! So what? I do not understand the philosophy of this...

UPDATE:

It turns out that there could be a situation where compiler can't know which method to choose (as pointed out by Tomasz Nurkiewicz), ok I understand.. but in my situation these two methods can clearly be distinguished. Here is the exact piece of code (with all original names and stuff preserved this time):

  def addAnim (name: String, x: Float, y: Float, tex: Buffer[Texture], fps: Int, percent: Float = 0): TImageSequence =
    addAnim (name, x, y, tex(0).getImage.getWidth, tex(0).getImage.getHeight, tex, fps, percent)

  def addAnim (name: String, x: Float, y: Float, w: Float, h: Float, tex: Buffer[Texture], fps: Int, percent: Float = 0): TImageSequence = {
     // do stuff
  }
3
It sounds like Scala disallows this feature because of the possibility of creating unresolvable ambiguity, even though some cases are not ambiguous. That being the case, your options are to give your functions different names, or to file a feature request with the Scala project.Ben
Even if in your case, it might work out fine, don't forget that other traits can be combined with your type. That might bring in more ambiguities. The decision taken by the Scala developers seems a little strict to me as well, and I share the notion that it seems as though it could be alleviated to some extent. But, hey, that's how it is. As @Ben pointed out, you can always file a feature request.Madoc

3 Answers

11
votes

It isn't possible to have two methods with default parameters and with the same name. Scala generates methods to obtain default values with names based on target method's name, so some sort of name collision may occur.

scala> object Test {
     |   def m(i: String = "Default value") {}
     | }
defined module Test

scala> Test.`m$default$1`
res0: String = Default value
6
votes

You are not showing your code, but here is a simple example:

object C {
  def addAnim(x: Int = 42) {}
  def addAnim(y: String = "abc") {}
}

If I now call:

C.addAnim()

which method should be invoked? The object C won't compile because the compiler is not capable of guessing which addAnim method do you mean when not providing any argument.

3
votes

Why not combine both methods in one by making w and h optional as well, e.g.

def addAnim (name: String, 
    x: Float, y: Float, 
    tex: Buffer[Texture], 
    fps: Int, 
    percent: Float = 0, 
    w: Float = Float.NaN, h:Float = Float.NaN): TImageSequence