2014-01-10 93 views
0

亚型我有一张地图,声明如下:铸造斯卡拉

private var iCacheMap: HashMap[Class[_ <: ICacheable], String] = .... 

因此,对于这个iCacheMap的关键是实现ICacheable接口

我再想找查询该地图的一类,如下:

private def queryICacheMap(message: AnyRef) { 
    val iCacheable = message.asInstanceOf[ICacheable] 
    val myString = iCacheMap.get(classOf[iCacheable]).get 
    // ...do something with myString 
} 

不过,我得到一个类型不匹配异常解释说,我们期待A类_ <:ICacheable],但实际是类[任何]

我需要做什么才能正确投射这些东西?

回答

6

您可以放心地使用模式匹配:

message match { 
    case iCacheable: ICacheable => iCacheMap.get(iCacheable.getClass).getOrElse("Not Found in Map") 
    case _ => //manage the "else" case 
} 

,当你有,你想了解信息的静态类型classOf [T]是有用的;如果您需要从实例中检索相同的信息,则可以使用getClass。

+0

不知道我遵循,在我上面的例子中的编译错误是为classOf [iCacheable。你能展示上述答案如何解决这个问题吗?谢谢 – DJ180

+0

我改进了这个例子。你必须使用getClass。 – Marco

0

试试这个:

var iCacheMap: Map[Class[_ <: ICacheable], String] = Map() 
//populate iCacheMap; message comes along 
myString = message match { 
    case iCacheable: ICacheable => iCacheMap.getOrElse(iCacheable.getClass, "Nothing") 
    case _ => throw new IllegalArgumentException("Not good") 
}