Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying map method to BitSet in Scala

With mutable BitSet, I tried to add the value 3 to all of its component, but I got this error.

val x = BitSet()
x.add(10); x.add(20)
x.map(_ + 3)

This is the message.

<console>:12: error: ambiguous implicit values:
 both method newCanBuildFrom in class SortedSetFactory of type [A](implicit ord: Ordering[A])scala.collection.generic.CanBuildFrom[scala.collection.mutable.SortedSet.Coll,A,scala.collection.mutable.SortedSet[A]]
 and method canBuildFrom in object BitSet of type => scala.collection.generic.CanBuildFrom[scala.collection.mutable.BitSet,Int,scala.collection.mutable.BitSet]
 match expected type scala.collection.generic.CanBuildFrom[scala.collection.mutable.BitSet,Int,That]
              x.map(_ + 3)

I could use BitSet(x.toArray.map(_ + 3): _*) to get the result that I expected, but I guess there might be better way. What's wrong with applying map in BitSet in Scala?

like image 245
prosseek Avatar asked Jun 04 '14 17:06

prosseek


1 Answers

You can use

x.map(_ + 3)(BitSet.canBuildFrom)

which is a bit closer to the original version of the code. The method map needs to create a new collection instance to produce the result, so it looks for an implicit method that it can use. However, matching of implicits is only performed based on the signature, and this way two candidates are found which leads to the error. I think this is a result of the rather complicated class and trait hierarchy in which some of the redundancy was not eliminated. The workaround is to provide the building method explicitly instead of relying on implicits.

like image 114
Michał Kosmulski Avatar answered Nov 01 '22 22:11

Michał Kosmulski