Why can't I create an array of general type?

This does not work:

def giveArray[T](elem:T):Array[T] = { new Array[T](1) } 

But it does:

  def giveList[T](elem:T):List[T] = { List.empty[T] } 

I'm sure this is a pretty simple thing, and I know that arrays can behave a bit unusual in Scala.

Can someone explain to me how to create such an array and why it doesn't work in the first place?

+8
arrays scala
source share
1 answer

This is due to JVM type erasure. A manifest was presented to handle this; they cast type information to type T. This will compile:

 def giveArray[T: Manifest](elem:T):Array[T] = { new Array[T](1) } 

There are almost duplicate questions in this question. Let me see if I can dig. 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)

What is required here is that you help the compiler by providing some runtime hint, what is the actual parameter like evenElems

In particular, you can also use ClassManifest .

 def giveArray[T: ClassManifest](elem:T):Array[T] = { new Array[T](1) } 

Related questions:

  • cannot find class manifest for element type T
  • What is a manifest in Scala and when do you need it?
  • About Scala generics: cannot find class manifest for element type T
+17
source share

All Articles