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)
^
答案 0 :(得分:7)
它正在解释它,好像你试图用2个参数调用+=
方法(而不是一个元组参数)。
尝试以下其中一项
x += ((1, 2))
val t = (1, 2)
x += t
x += 1 -> 2 //syntactic sugar for new tuple
请注意,编译器无法确定您是否尝试使用单个元组参数调用该方法,因为有多个+=
重载:
def +=(elem : A) : Growable.this.type
def +=(elem1 : A, elem2 : A, elems : A*) : Growable.this.type
这里没有第二个重载,编译器可以解决它。以下示例可能会澄清:
class Foo {
def bar(elem: (Int, Int)) = ()
def baz(elem: (Int, Int)) = ()
def baz(elem1: (Int, Int), elem2: (Int, Int)) = ()
}
以您bar
的方式呼叫+=
现在有效,但有警告:
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.
以您调用baz
的方式调用+=
失败,但出现类似错误:
f.baz(3, 4)
error: type mismatch;