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?
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
.
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