9

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?

Plankalkül
  • 833
  • 8
  • 21

1 Answers1

19

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:

Community
  • 1
  • 1
huynhjl
  • 41,520
  • 14
  • 105
  • 158
  • I assumed it was asked many times before but I couldn't find anything. Thanks for answering it again :) – Plankalkül May 21 '11 at 23:43
  • Oh I never answered this one before. I asked the same question a while back :) I think in this case you would have eventually stumbled on it if you searched with "scala" and the error message. – huynhjl May 21 '11 at 23:53
  • 3
    To be more precise, this is because `T` is erased but arrays _are not_. Of note too, `ClassManifest` is faster. – Daniel C. Sobral May 22 '11 at 02:47
  • 3
    Also, Java does not have this problem because you can't pass primitives as generics in java, whereas you can in Scala. In other words, you can't create an `Array giveArray` in Java that returns `Array`, but `giveArray[T]` in Scala can. I think this is an important point to make. – Daniel C. Sobral May 22 '11 at 02:49