【问题标题】:Appending tuple to a MutableList of tuples is giving an error将元组附加到元组的 MutableList 会出错
【发布时间】:2015-01-04 21:12:50
【问题描述】:
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)
                ^

【问题讨论】:

    标签: scala tuples scala-collections


    【解决方案1】:

    将其解释为您尝试使用 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;
    

    【讨论】:

    • 需要明确的是,+= 已重载,采用一个元素或 2+ 个元素。否则,您将得到 args 的元组,并且语法有效。
    • 不是吹毛求疵,而是为了避免混淆,在-Ywarn-adapted-args-Xlint 下发出警告。有些改编比其他改编更邪恶。
    猜你喜欢
    • 2013-12-23
    • 1970-01-01
    • 2020-04-03
    • 2021-07-04
    • 1970-01-01
    • 2011-03-17
    • 2018-08-18
    • 2014-02-24
    相关资源
    最近更新 更多