【发布时间】:2015-06-05 05:39:23
【问题描述】:
这是我的基本 CMap,它将类(任何 T 的 Class[T])映射到任何类型的值。
scala> type CMap = Map[Class[T] forSome{type T}, Any]
defined type alias CMap
scala> val cMap: CMap = Map(classOf[Int]->5, classOf[String]->"abc", classOf[Double]->"ddd")
cMap: CMap = Map(int -> 5, class java.lang.String -> abc, double -> ddd)
现在我想要一个“绑定”CMap(称之为 CMapBind)。像 CMap 一样,它将类(任何类)映射到值(任何值)。但与 CMap 不同的是,CMapBind 在键和值之间具有类型绑定,这意味着我希望以下行为:
val cMapBind: CMapBind = Map(classOf[Int]->5, classOf[String]-> "aa") // should compile
val cMapBind: CMapBind = Map(classOf[Int]->5, classOf[String]-> 0) // should fail compile
如何实现 CMapBind?
我知道以下两个在语法/逻辑上不起作用。
scala> type CMapBind = Map[Class[T] forSome{type T}, T]
<console>:8: error: not found: type T
type CMapBind = Map[Class[T] forSome{type T}, T]
scala> type CMapBind = Map[Class[T], T] forSome{type T}
scala> val cMapBind: CMapBind = Map(classOf[Int]->5, classOf[String]->"str")
<console>:8: error: type mismatch;
found : scala.collection.immutable.Map[Class[_ >: String with Int],Any]
required: CMapBind
(which expands to) Map[Class[T],T] forSome { type T }
val cMapBind: CMapBind = Map(classOf[Int]->5, classOf[String]->"str")
请注意,这里我使用类型构造函数 Class[T] 作为示例来说明问题。在我的代码中,我有自己的类型,例如trait Animal[S, T], class Dog extends Animal[Int, String]。
编辑 1: 我应该提到我以不可变 Map 为例,但我真正需要的是可变异构 Map)。
【问题讨论】:
-
不确定是否可能(以您想要的方式),因为类型擦除。这个映射总是会丢失值类型(到上限
Any),并且键类型总是混合的。认为您需要一种异构的Map,来保存类型。 -
是的,像
HMap和shapeless这样的异构地图是我正在查看的。 -
你不能用shapeless,你要自己用吗?因为无形它非常好:)
-
我很乐意使用
shapeless的HMap,如果它有效的话。在我的应用程序中,我想要一个“可变”的异构地图。我的理解是HMap是不可变的。
标签: scala collections existential-type