[英]Scala generic wildcard and specific type
我有mappings
值:
val mappings: Map[Class[_] ,Iterable[AttributeKeyAndValue] => AnyRef]
是否有可能使其更加类型安全
val mappings: Map[Class[T], Iterable[AttributeKeyAndValue] => T]
其中T
与下划线相同。 如果它符合以下代码,我希望编译器会抱怨:
val mappings: Map[Class[T], Iterable[AttributeKeyAndValue] => T] = Map(
classOf[String], attrs => 1)
您不能参数化val
所以不能,不是那样。
看着你的要求,没有多大意义。 可以这样说: val mappings: Map[Class[T], Iterable[AttributeKeyAndValue] => T]
是有效的,编译器会抱怨。
您可以参数化映射中具有相同类型的所有条目,即。 T
或每个条目都有其自己的参数化类型,从而在使用apply
或get
方法检索条目时无法知道它是哪种类型。
我建议您坚持使用Class[_]
因为对此进行参数化的唯一方法是强制所有条目具有相同的类型。 例如,如果您可以在Map[Class[String], ...]
对其进行参数化Map[Class[String], ...]
那么您将只能在地图中放置1个条目,其中键为classOf[String]
那个条目
Scala中的通配符只是存在类型的一种特定的简单情况,而您想要的则更复杂,因为您想在两个地方使用相同的T
像Seq[(Class[T], AttributeKeyAndValue => T) forSome { type T }]
。 但是请注意您需要放置forSome
:如果想要Map
,就没有等效的位置! 例如Map[Class[T], AttributeKeyAndValue => T] forSome { type T }
表示整个地图只有一个T
我建议创建一个呈现更类型安全的接口的类型,即使您需要在内部进行强制转换:
class Mappings private (contents: Map[Class[_], Iterable[AttributeKeyAndValue] => AnyRef]) {
def get[T](clazz: Class[T]) = contents.get(clazz).asInstanceOf[Option[Iterable[AttributeKeyAndValue] => T]]
def +[T](clazz: Class[T], value: Iterable[AttributeKeyAndValue] => T) = new Mappings(contents + (clazz, value))
// any other methods you want
}
object Mappings {
val empty = new Mappings(Map.empty)
}
// elsewhere
Mappings.empty + (classOf[String], attrs => "a") // type-checks
Mappings.empty + (classOf[String], attrs => 1) // doesn't type-check
实际上,您可以改进API以避免手动传递类,因此您只需编写get[String]
和+(attrs => 1)
自动推断出它需要classOf[Int]
,但是我决定在这里展示一个简单的想法。
好了,编译器不知道您提供的示例中的T
是什么。 因此,作为一种选择,您可以定义由T
参数化的mappings
函数:
def mappings[T](x: AttributeKeyAndValue => T):
Map[Class[T], AttributeKeyAndValue => T] = Map(classOf[T] -> x)
用法:
val mappping = mappings(x => x.toString)
编译器可以推断的类型是:
mappping : Map[Class[String], AttributeKeyAndValue => String]
将其包装成案例类吗?
type Attrs = Iterable[AttributeKeyAndValue]
case class Mappings[T](m: Map[Class[T], Attrs => T]
object Mappings {
implicit def mk[T](m: Map[Class[T], Attrs => T): Mappings[T] = Mappings(m)
}
val mappings: Mappings[_] = Map(classOf[String] -> { (_:Attrs) => "foo" }) // Works
val badMappings: Mappings[_] = Map(classOf[String] -> { (_:Attrs) => 1 }) // Fails
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.