简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM