找不到元素类型 T 的类清单

发布于 2024-08-21 11:47:49 字数 542 浏览 3 评论 0原文

试图从 这个问题编译一些代码 并遇到此错误消息无法找到元素类型 T 的类清单。这是显示该行为的另一个片段:

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) 修复了该问题。显然提供清单是另一种选择......但是“提供清单意味着”是什么?

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) }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时间海 2024-08-28 11:47:49

要提供类型信息,您可以使用上下文绑定

def f[T : Manifest](a:T, b:T):Array[T] = { new Array[T](2) }

或清单作为隐式参数:

def f[T](a:T, b:T)(implicit manifest : Manifest[T]) : Array[T] = { new Array[T](2) }

前者是后者的语法糖。需要 manifest 因为有关 T 的类型信息是由于 JVM 的通用类型错误而丢失。

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) }

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文