Ted
Ted

Reputation: 33

Appending tuple to a MutableList of tuples is giving an error

scala> val x = mutable.MutableList[(Int, Int)]()
x: scala.collection.mutable.MutableList[(Int, Int)] = MutableList()

scala> x += (1, 2)
<console>:10: error: type mismatch;
found   : Int(1)
required: (Int, Int)
          x += (1, 2)
                ^

Upvotes: 3

Views: 1812

Answers (1)

Ben Reich
Ben Reich

Reputation: 16324

It is interpreting it as if you're trying to call the += method with 2 parameters (as opposed to one tuple parameter).

Try one of the following instead

x += ((1, 2))

val t = (1, 2)
x += t

x += 1 -> 2 //syntactic sugar for new tuple

Note that the compiler can't figure out that you're trying to call the method with a single tuple parameter because there are multiple += overloads:

def +=(elem : A) : Growable.this.type
def +=(elem1 : A, elem2 : A, elems : A*) : Growable.this.type 

Without the second overload here, the compiler could figure it out. The following example may clarify:

class Foo {
    def bar(elem: (Int, Int)) = ()
    def baz(elem: (Int, Int)) = ()
    def baz(elem1: (Int, Int), elem2: (Int, Int)) = ()
}

Calling bar in the way you called += now works, but with a warning:

foo.bar(2, 3) //No confounding overloads, so the compiler can figure out that we meant to use a tuple here
warning: Adapting argument list by creating a 2-tuple: this may not be what you want.

Calling baz in the way you called += fails, with a similar error:

f.baz(3, 4)
error: type mismatch;

Upvotes: 7

Related Questions