Adding Two Set [Any]

Adding two Set[Int] works:

 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) 

But adding two Set[Any] doesn't mean:

 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) ^ 

Any suggestion to get around this error?

+6
scala scala-collections
source share
4 answers

It works:

 Set[Any](1, 2, 3).++[Any, Set[Any]](Set[Any](4, 5, 6)) 

But ugly as sin. The compiler is confused as to whether to use the Addable method or one of the TraversableLike that has an implicit parameter. They don’t have the same whitefish, but syntactic sugar makes it look like they are doing it. Tell which one to use and the compiler is happy.

I guess the reason it works for Ints is because they don't have subtypes.

This will call the Addable method if it matters to you:

 Set[Any](1, 2, 3).asInstanceOf[collection.generic.Addable[Any, Set[Any]]] ++ Set[Any](4, 5, 6) 
+5
source share

Using the alias union seems to work,

 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) 

I'm still wondering if there is a way to use ++ .

+9
source share

This works, but won’t win the “Beautiful Code Contest":

 Set[Any](1,2,3).++[Any,Set[Any]](Set[Any](4,5,6)) 
+3
source share
 val s:scala.collection.TraversableLike[Any, Set[Any]] = Set(1,2,3) val t:Set[Any] = Set(3,4,5) s ++ t 

Check out this one more post in the ugliest code .;)

+3
source share

All Articles