Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find implicit value for evidence parameter of type scala.reflect.ClassManifest[T]

Tags:

types

scala

It seems I don't understand something important, maybe about erasure (damn it).

I have a method, which I wanted to create array of size n filled with values from gen:

def testArray[T](n: Int, gen: =>T) {
  val arr = Array.fill(n)(gen)
  ...
}

And use it, for example as:

testArray(10, util.Random.nextInt(10))

But I get error:

scala: could not find implicit value for evidence parameter of type scala.reflect.ClassManifest[T]
val arr = Array.fill(n)(gen)
                       ^

Please, explain what I did wrong, why this error, and what kind of code it makes impossible?

like image 625
dmitry Avatar asked Feb 10 '13 09:02

dmitry


1 Answers

That is because in testArray the concrete type of T is not known at compile time. Your signature has to look like def testArray[T : ClassManifest](n: Int, gen: =>T), this will add an implicit parameter of type ClassManifest[T] to your method, that is automatically passed to the call of testArray and then further passed to the Array.fill call. This is called a context bound.

like image 84
drexin Avatar answered Oct 26 '22 13:10

drexin