Enumeration and mapping with Scala 2.10

I am trying to port the application to Scala 2.10.0-M2. I see good improvements with better warnings from the compiler. But I also got a bunch of bugs, all related to me mapping from Enumeration.values .

I will give you a simple example. I would like to have an enumeration, and then pre-create a bunch of objects and build a map that uses the enumeration values โ€‹โ€‹as keys, and then some relevant objects as values. For instance:

 object Phrase extends Enumeration { type Phrase = Value val PHRASE1 = Value("My phrase 1") val PHRASE2 = Value("My phrase 2") } class Entity(text:String) object Test { val myMapWithPhrases = Phrase.values.map(p => (p -> new Entity(p.toString))).toMap } 

Now it was used to work fine on Scala 2.8 and 2.9. But 2.10.0-M2 gives me the following warning:

 [ERROR] common/Test.scala:21: error: diverging implicit expansion for type scala.collection.generic.CanBuildFrom[common.Phrase.ValueSet,(common.Phrase.Value, common.Entity),That] [INFO] starting with method newCanBuildFrom in object SortedSet [INFO] val myMapWithPhrases = Phrase.values.map(p => (p -> new Entity(p.toString))).toMap ^ 

What causes this and how do you fix it?

+4
source share
2 answers

This is basically a type mismatch error. You can get around it by first converting to a list:

 scala> Phrase.values.toList.map(p => (p, new Entity(p.toString))).toMap res15: scala.collection.immutable.Map[Phrase.Value,Entity] = Map(My phrase 1 -> Entity@d0e999 , My phrase 2 -> Entity@1987acd ) 

For more information, see the answers to What does the meaning of the scalar message โ€œdiverging implicit extensionโ€ mean? and What is the rejection of an implicit extension error?

+4
source

As you can see from your error, the ValueSet, which contains the enumerations, at some point became a SortedSet. He wants to create a SortedSet on the map, but cannot sort your Entity.

Something like this works with the case Entity class:

 implicit object orderingOfEntity extends Ordering[Entity] { def compare(e1: Entity, e2: Entity) = e1.text compare e2.text } 
+1
source

Source: https://habr.com/ru/post/1398870/


All Articles