tags:

views:

131

answers:

1

For a function as below:

def reverse[T](a: Array[T]): Array[T] = {
    val b = new Array[T](a.length)
    for (i <- 0 until a.length)
        b(i) = a(a.length -i - 1)
    b
}

I am getting "error: cannot find class manifest for element type T" from line 2.

Is there anyway to solve this?

+6  A: 

Simply add a context bound ClassManifest to your method declaration:

def reverse[T : ClassManifest](a: Array[T]): Array[T] = ...

In order to construct an array, the array's concrete type must be known at compile time. This type is supplied by the compiler via an implicit ClassManifest parameter. That is, the signature of the Array constructor is actually

Array[T](size: Int)(implicit m: ClassManifest[T]): Array[T]

In order to supply this parameter, there must be a ClassManifest in scope when the Array constructor is invoked. Therefore, your reverse method must also take an implicit ClassManifest parameter:

def reverse[T](a: Array[T])(implicit m: ClassManifest[T]): Array[T] = ...
// or equivalently
def reverse[T : ClassManifest](a: Array[T]): Array[T] = ...

The latter, simpler notation is called a context bound.

Aaron Novstrup
One can use `Manifest` instead of `ClassManifest` in the context bound. What´s the difference?
michael.kebe
Good question. Just trying to figure out the same thing myself :-)
Aaron Novstrup
It appears that Manifest is a type alias for scala.reflect.Manifest, which is not documented in the ScalaDoc (maybe because it's compiler magic?). For that reason, I'd tend to prefer ClassManifest just for clarity
Aaron Novstrup
`ClassManifest` requires only that the compiler knows the class of the type. `Manifest` requires that the compiler knows all its type parameters too. Eg. for `List[String]`, the former only needs knowledge of `List` whereas the latter needs `List[String]`. To create a Java array, you only need the former.
Ben Lings
@Ben Great info, thanks!
Aaron Novstrup
The ClassManifest vs Manifest question has been answered in more detail at http://stackoverflow.com/questions/3213510/what-is-a-manifest-in-scala-and-when-do-you-need-it
Aaron Novstrup