我正在尝试制作自定义异构列表和地图。尽管有使用 Manifest 的示例,但在 Scala 2.10 中它们已被弃用,我应该使用 TypeTags(或 Classtags)。在地图的情况下,我似乎可以使用(例如)元组 String->(TypeTag[ _ <: Any ], Any ) 保留 Any 与 Type 的绑定。
我的问题是如何从恢复的 TypeTag 和未定义的 T 中获取能够返回 TypeTag.tpe 的实例 - 在我拥有的代码中
//** How do I use saved typeTag to define T here?**
正如所写,get 方法中没有编译器错误,但 T 设置为 Nothing 并返回 Some(Nothing)。我希望我的注释行起作用:
case Some( x ) => // println( "Get 2*'pi'=" + x*2 )
在有编译器消息的地方,“值 * 不是 Nothing 的成员”。我意识到我可以写得更紧凑,但完成后,我可以将鼠标悬停在我的 IDE 中并一步一步地跟随。有一个相关的问题 - Scala:什么是 TypeTag 以及如何使用它? 但它似乎并没有走到“最后一英里” - 重新标记任何。
这个怎么做?
这是我到目前为止的代码:
import scala.reflect._
import scala.reflect.runtime.universe._
import collection.mutable.Map
object Test extends HMap {
def main( args: Array[ String ] ) {
var hmap = new HMap
hmap( "anInt" ) = 1
hmap( "pi" ) = 3.1416f
hmap( "c" ) = "hello"
// Test
val result = hmap.get( "pi" )
result match {
case Some( x ) =>
println( "Get 'pi'=" + x*2 )
case _ =>
}
}
}
class HMap {
private var coreMap =
Map.empty[ String, ( TypeTag[ _ <: Any ], Any ) ]
// Save the type tag with the value
def update[ T: TypeTag ]( key: String, value: T ) =
coreMap.put( key, ( typeTag[ T ], value ) )
override def toString = coreMap.toString
def get[ T: TypeTag ]( key: String ): Option[ T ] = {
val option = coreMap.get( key )
val result = option match {
case None => None
case Some( x ) => {
val typeTag = x._1; val value = x._2
println( "Matched Type = " +
typeTag.tpe + " Value=" + value )
// **** How do I use saved typeTag to define T here? ****
val v = value.asInstanceOf[ T ]
val s = Some( v )
println( "Returning " + s )
s
}
}
result
}
}