Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Scala中创建类型对象的集合_Scala_Collections_Type Systems - Fatal编程技术网

如何在Scala中创建类型对象的集合

如何在Scala中创建类型对象的集合,scala,collections,type-systems,Scala,Collections,Type Systems,基本上,我希望有一个按类型对象索引的映射。在本例中,我尝试使用类作为“类型” 以下代码: class SuperClass {} val typemap = new HashMap[Class[_ <: SuperClass], SuperClass] def insertItem1[T <: SuperClass] (item : T) = typemap += classOf[T] -> item def insertItem2[T <: SuperClass] (

基本上,我希望有一个按类型对象索引的映射。在本例中,我尝试使用类作为“类型”

以下代码:

class SuperClass {}
val typemap = new HashMap[Class[_ <: SuperClass], SuperClass]

def insertItem1[T <: SuperClass] (item : T) = typemap += classOf[T] -> item
def insertItem2[T <: SuperClass] (item : T) = typemap += item.getClass -> item
和(2)item.getClass的类型错误:

Type mismatch, expected: Class[_ <: SuperClass], actual: Class[_]

显然,我可以在
insertItem
中使用asInstanceOf方法,并将该类作为参数传递给
isPresent
。有更好的方法吗?

问题再次在于泛型在运行时不可用。编译器的任务是找出
T
是什么,但它不能,因为它只能在运行时知道


您可以使用清单来获取该信息:。

您可以使用清单来实现这一点:

class TypeMap extends HashMap[Class[_], Any] {
    def putThing[T](t: T)(implicit m: Manifest[T]) = put(m.erasure, t)
}

val map = new TypeMap
map.putThing(4)
map.get(classOf[Int]) // returns Option[Any] = Some(4)

您正在通过擦除丢失类型,因此需要使用清单将隐式参数添加到包含类名称的Putting中。

为什么需要按类型存储和检索对象?我想知道,如果给定更多的上下文,没有一个不同的解决方案不涉及
classOf
getClass
。。我相信这是@huynhjl的副本。用例是一个实体系统,我希望基本上能够检索给定类型的所有(注册)对象。所以我可以为每种类型定义一种特殊的键,但是类对象就是那个键。如果没有泛型,我可以简单地将类对象作为键传递,然后它就可以正常工作了。但我认为有更好的方法。我不明白的是,如何在Putting中不被擦除-毕竟,我可以通过
t.getClass
获得它,所以必须在运行时知道它。
def isPresent[T <: SuperClass] = typemap contains classOf[T]
class TypeMap extends HashMap[Class[_], Any] {
    def putThing[T](t: T)(implicit m: Manifest[T]) = put(m.erasure, t)
}

val map = new TypeMap
map.putThing(4)
map.get(classOf[Int]) // returns Option[Any] = Some(4)