Scala 2.10的枚举和映射 [英] Enumeration and mapping with Scala 2.10
问题描述
我正在将我的应用程序移植到Scala 2.10.0-M2。我看到一些很好的改进,更好的警告从编译器。但是我也有一些错误,所有这些都与我有关,从 Enumeration.values
映射。
我会给你是一个简单的例子。我想有一个枚举,然后预先创建一堆对象,并构建一个使用枚举值作为键,然后一些匹配对象作为值的映射。例如:
对象短语扩展枚举{
type Phrase = Value
val PHRASE1 = Value(我的短语1)
val PHRASE2 =值(我的短语2)
}
类实体(文本:字符串)
对象测试{
val myMapWithPhrases = Phrase.values.map(p =>(p - > new Entity(p.toString)))toMap
}
现在这个在Scala 2.8和2.9上工作得很好。但是2.10.0-M2给了我以下警告:
[ERROR] common / Test.scala:21:error:diverged implicit扩展类型scala.collection.generic.CanBuildFrom [common.Phrase.ValueSet,(common.Phrase.Value,common.Entity),那]
$
[INFO]以方法newCanBuildFrom开头的对象SortedSet
[ INFO] val myMapWithPhrases = Phrase.values.map(p =>(p - > new Entity(p.toString)))。toMap
^
解决方案p $ p
它基本上是一个类型不匹配的错误。您可以通过首先转换为列表来解决问题:
scala> Phrase.values.toList.map(p =>(p,new Entity(p.toString)))。toMap
res15:scala.collection.immutable.Map [Phrase.Value,Entity] = Map(My短语1 - > Entity @ d0e999,我的短语2 - > Entity @ 1987acd)
信息,请参阅什么是分歧隐式扩展scalac消息的答案?和什么是分歧的隐式扩展错误?
I'm trying to port my application to Scala 2.10.0-M2. I'm seeing some nice improvements with better warnings from compiler. But I also got bunch of errors, all related to me mapping from
Enumeration.values
.I'll give you a simple example. I'd like to have an enumeration and then pre-create bunch of objects and build a map that uses enumeration values as keys and then some matching objects as values. For example:
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 this used to work just fine on Scala 2.8 and 2.9. But 2.10.0-M2 gives me 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's causing this and how do you fix it?
解决方案It's basically a type mismatch error. You can work around it by first converting is 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's a "diverging implicit expansion" scalac message mean? and What is a diverging implicit expansion error?
这篇关于Scala 2.10的枚举和映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!