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?
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.
No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.
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.
Both ArrayList and vector are generic types. But the C++ vector template overloads the [] operator for convenient element access.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With