Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala arrays and parameterized types

I'm trying to define a generic class that takes a parameterized type T and then use the type in an Array definition in the class. I wrote the following which I thought seemed like it should work

class MyClass[T] {

  val myarr:Array[T] = new Array[T](10)

}

But the compiler complains with the following

  • can't find the class manifest for element type T
  • value newArray is not a member of Null

Anyone know whats going on here and what its not happy about?

like image 224
sgargan Avatar asked Jan 18 '23 19:01

sgargan


1 Answers

The compiler needs to know how to instantiate things of type T. In the traditional Java way of handling generics through type erasure, this cannot reasonably be done; the compiler just says, "Hey, I don't know what T is, so I don't feel so great about allowing you to instantiate a T like that." In Scala, however, there is a word-around for this: manifests. In order to include the manifest for T, just change the first line of that code to

class MyClass[T : Manifest] {

That's it.

like image 146
Destin Avatar answered Jan 29 '23 00:01

Destin