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?

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

4 Comments

I assumed it was asked many times before but I couldn't find anything. Thanks for answering it again :)
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.
To be more precise, this is because T is erased but arrays are not. Of note too, ClassManifest is faster.
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<T> giveArray<T> in Java that returns Array<int>, but giveArray[T] in Scala can. I think this is an important point to make.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.