This does not work:
这不起作用:
def giveArray[T](elem:T):Array[T] = {
new Array[T](1)
}
But this does:
但这样做:
def giveList[T](elem:T):List[T] = {
List.empty[T]
}
I am sure this is a pretty basic thing and I know that Arrays can behave a bit unusual in Scala.
我确信这是一个非常基本的东西,我知道Arrays在Scala中的行为有点不寻常。
Could someone explain to me how to create such an Array and also why it doesn't work in the first place?
有人可以向我解释如何创建这样一个数组,以及为什么它不起作用?
1 个解决方案
#1
18
This is due to JVM type erasure. Manifest were introduce to handle this, they cause type information to be attached to the type T. This will compile:
这是由于JVM类型擦除。引入Manifest来处理这个问题,它们会将类型信息附加到类型T上。这将编译:
def giveArray[T: Manifest](elem:T):Array[T] = {
new Array[T](1)
}
There are nearly duplicated questions on this. Let me see if I can dig up. See http://www.scala-lang.org/docu/files/collections-api/collections_38.html for more details. I quote (replace evenElems with elem in your case)
对此有几乎重复的问题。让我看看我是否可以挖掘。有关详细信息,请参阅http://www.scala-lang.org/docu/files/collections-api/collections_38.html。我引用(在你的情况下用elem替换evenElems)
What's required here is that you help the compiler out by providing some runtime hint what the actual type parameter of evenElems is
这里需要的是通过提供一些运行时提示来帮助编译器,提示evenElems的实际类型参数是什么
In particular you can also use ClassManifest
.
特别是你也可以使用ClassManifest。
def giveArray[T: ClassManifest](elem:T):Array[T] = {
new Array[T](1)
}
Similar questions:
类似的问题:
- cannot find class manifest for element type T
- 找不到元素类型T的类清单
- What is a Manifest in Scala and when do you need it?
- 什么是Scala中的Manifest,什么时候需要它?
- About Scala generics: cannot find class manifest for element type T
- 关于Scala泛型:找不到元素类型T的类清单
#1
18
This is due to JVM type erasure. Manifest were introduce to handle this, they cause type information to be attached to the type T. This will compile:
这是由于JVM类型擦除。引入Manifest来处理这个问题,它们会将类型信息附加到类型T上。这将编译:
def giveArray[T: Manifest](elem:T):Array[T] = {
new Array[T](1)
}
There are nearly duplicated questions on this. Let me see if I can dig up. See http://www.scala-lang.org/docu/files/collections-api/collections_38.html for more details. I quote (replace evenElems with elem in your case)
对此有几乎重复的问题。让我看看我是否可以挖掘。有关详细信息,请参阅http://www.scala-lang.org/docu/files/collections-api/collections_38.html。我引用(在你的情况下用elem替换evenElems)
What's required here is that you help the compiler out by providing some runtime hint what the actual type parameter of evenElems is
这里需要的是通过提供一些运行时提示来帮助编译器,提示evenElems的实际类型参数是什么
In particular you can also use ClassManifest
.
特别是你也可以使用ClassManifest。
def giveArray[T: ClassManifest](elem:T):Array[T] = {
new Array[T](1)
}
Similar questions:
类似的问题:
- cannot find class manifest for element type T
- 找不到元素类型T的类清单
- What is a Manifest in Scala and when do you need it?
- 什么是Scala中的Manifest,什么时候需要它?
- About Scala generics: cannot find class manifest for element type T
- 关于Scala泛型:找不到元素类型T的类清单