问题描述
似乎我不明白一些重要的事情,也许是关于擦除(该死的).
It seems I don't understand something important, maybe about erasure (damn it).
我有一个方法,我想创建大小为 n
的数组,其中填充了来自 gen
的值:
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)
...
}
并使用它,例如:
testArray(10, util.Random.nextInt(10))
但我得到错误:
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?
推荐答案
那是因为 testArray
中 T
的具体类型在编译时是未知的.您的签名必须看起来像 def testArray[T : ClassManifest](n: Int, gen: =>T)
,这将添加类型为 ClassManifest[T]
的隐式参数code> 到您的方法,它会自动传递给 testArray
的调用,然后进一步传递给 Array.fill
调用.这称为上下文绑定
.
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
.
这篇关于找不到 scala.reflect.ClassManifest[T] 类型的证据参数的隐式值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!