Scala 通用方法 - 没有可用于 T 的 ClassTag
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16921168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala generic method - No ClassTag available for T
提问by Chuck
I'm relatively new to Scala and am trying to define a generic object method. However, when I refer to the parameterized type within the method I am getting "No ClassTag available for T". Here is a contrived example that illustrates the problem.
我对 Scala 比较陌生,正在尝试定义一个通用的对象方法。但是,当我在方法中引用参数化类型时,我得到“T 没有可用的 ClassTag”。这是一个说明问题的人为示例。
scala> def foo[T](count: Int, value: T): Array[T] = Array.fill[T](count)(value)
<console>:7: error: No ClassTag available for T
def foo[T](count: Int, value: T): Array[T] = Array.fill[T](count)(value)
^
Thanks in advance for help in understanding what is wrong here and how to make this contrived example work.
在此先感谢您帮助理解这里出了什么问题以及如何使这个人为的示例工作。
回答by Régis Jean-Gilles
To instantiate an array in a generic context (instantiating an array of Twhere Tis a type parameter), Scala needs to have information at runtime about T, in the form of an implicit value of type ClassTag[T].
Concretely, you need the caller of your method to (implicitly) pass this ClassTagvalue, which can conveniently be done using a context bound:
为了在泛型上下文中实例化一个数组(实例化一个TwhereT是一个类型参数的数组),Scala 需要在运行时T以 type 的隐式值的形式获得about 的信息ClassTag[T]。具体来说,您需要方法的调用者(隐式)传递此ClassTag值,这可以使用上下文绑定方便地完成:
def foo[T:ClassTag](count: Int, value: T): Array[T] = Array.fill[T](count)(value)
For a (thorough) description of this situation, see this document:
有关此情况的(彻底)描述,请参阅此文档:
http://docs.scala-lang.org/sips/completed/scala-2-8-arrays.html
http://docs.scala-lang.org/sips/completed/scala-2-8-arrays.html
(To put it shortly, ClassTags are the reworked implementation of ClassManifests, so the rationale remains)
(简而言之,ClassTags 是 ClassManifests 的重新实现,所以基本原理仍然存在)

