Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

scala

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.

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

like image 849
Plankalkül Avatar asked May 21 '11 23:05

Plankalkül


People also ask

Why can't you create a generic array Java?

If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.

Can you create an array of generic type?

No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.

Can you make an array of generics in Java?

Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.

Can ArrayList be generic?

Both ArrayList and vector are generic types. But the C++ vector template overloads the [] operator for convenient element access.


1 Answers

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:

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)

What's required here is that you help the compiler out by providing some runtime hint what the actual type parameter of evenElems is

In particular you can also use ClassManifest.

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

Similar 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
like image 133
huynhjl Avatar answered Oct 18 '22 16:10

huynhjl