找不到元素类型 T 的类清单 [英] cannot find class manifest for element type T
问题描述
试图从 编译一些代码这个SO问题并遇到此错误消息cannot find class manifest for element type T
.这是显示行为的另一个片段:
Was trying to compile some code from this SO question and run into this error message cannot find class manifest for element type T
. Here is another snippet that shows the behavior:
scala> def f[T](a:T, b:T):Array[T] = { new Array[T](2) }
<console>:4: error: cannot find class manifest for element type T
def f[T](a:T, b:T):Array[T] = { new Array[T](2) }
我可以看到 new collection.mutable.GenericArray[T](2)
解决了这个问题.显然提供清单是另一种选择……但是提供清单意味着什么"?
I can see that new collection.mutable.GenericArray[T](2)
fixes the issue. Apparently providing a manifest is the other option... But what does "providing a manifest mean"?
推荐答案
要提供类型信息,您可以使用上下文绑定
To provide type information you can use a context bound
def f[T : Manifest](a:T, b:T):Array[T] = { new Array[T](2) }
或作为隐式参数的清单:
or the manifest as an implicit argument:
def f[T](a:T, b:T)(implicit manifest : Manifest[T]) : Array[T] = { new Array[T](2) }
前者是后者的语法糖.需要 manifest 因为关于 T 的类型信息是由于 JVM 的通用类型错误而丢失.
The former is syntactic sugar for the later. The manifest is needed because the type information about T is missing due to generic type errasure of the JVM.
这篇关于找不到元素类型 T 的类清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!