添加两个[任意]

Ale*_*ert 7 scala scala-2.8 scala-collections

添加两Set[Int]件作品:

Welcome to Scala version 2.8.1.final (Java HotSpot(TM) Server VM, Java 1.6.0_23).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Set(1,2,3) ++ Set(4,5,6)          
res0: scala.collection.immutable.Set[Int] = Set(4, 5, 6, 1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

但添加两个Set[Any]不是:

scala> Set[Any](1,2,3) ++ Set[Any](4,5,6)
<console>:6: error: ambiguous reference to overloaded definition,
both method ++ in trait Addable of type (xs: scala.collection.TraversableOnce[Any])scala.collection.immutable.Set[Any]
and  method ++ in trait TraversableLike of type [B >: Any,That](that: scala.collection.TraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Set[Any],B,That])That
match argument types (scala.collection.immutable.Set[Any])
   Set[Any](1,2,3) ++ Set[Any](4,5,6)
           ^
Run Code Online (Sandbox Code Playgroud)

有什么建议可以解决这个错误吗?

Ale*_*ert 12

看起来像使用别名的union作品,

scala> Set[Any](1,2,3) union Set[Any](4,5,6)
res0: scala.collection.immutable.Set[Any] = Set(4, 5, 6, 1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

如果有一种方法可以使用,我仍然很好奇++.


sbl*_*ndy 5

这有效:

Set[Any](1, 2, 3).++[Any, Set[Any]](Set[Any](4, 5, 6))
Run Code Online (Sandbox Code Playgroud)

但是作为罪恶是丑陋的.编译器对于是否在Addable上使用该方法或在TraversableLike上使用该方法感到困惑,该方法具有隐式参数.它们没有相同的信号,但是语法糖使它看起来好像它们一样.告诉它使用哪一个,编译器很高兴.

我想它对Ints起作用的原因是它们没有任何亚型.

这将调用Addable上的方法,如果这对您很重要:

Set[Any](1, 2, 3).asInstanceOf[collection.generic.Addable[Any, Set[Any]]] ++ Set[Any](4, 5, 6)
Run Code Online (Sandbox Code Playgroud)