Scala通用方法 - 没有可用于T的ClassTag [英] Scala generic method - No ClassTag available for T
问题描述
我对Scala相对陌生,正在尝试定义一个通用对象方法。但是,当我在方法中引用参数化类型时,我会得到No T Tag for T available for。这是一个可以说明问题的人为的例子。
scala> def foo [T](count:Int,value:T):Array [T] = Array.fill [T](count)(value)
是一个类型参数),Scala需要在运行时拥有
< console>:7:error:No ClassTag available for T
def foo [T](count:Int,value:T):Array [T] = Array.fill [T](count)(value)
^
$ c $
$ b感谢您提前帮助理解此处出现的问题以及如何使这个人为的示例有效。 class =h2_lin>解决方案
在一般上下文中实例化一个数组
T
的信息,形式为ClassTag [T]
。
具体而言,您需要方法调用者(隐式地)传递ClassTag 值,这可以方便地使用上下文绑定: def foo [T:ClassTag](count:Int,value:T):Array [T] = Array。填充[T](计数)(值)
关于这种情况的详细描述,此文件:
http://docs.scala-lang.org/sips/completed/scala-2-8-arrays.html
(简而言之,ClassTags是ClassManifests的重新实现,因此基本原理仍然存在)
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> 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.
解决方案To instantiate an array in a generic context (instantiating an array of
T
whereT
is a type parameter), Scala needs to have information at runtime aboutT
, in the form of an implicit value of typeClassTag[T]
. Concretely, you need the caller of your method to (implicitly) pass thisClassTag
value, which can conveniently be done using a context bound: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
(To put it shortly, ClassTags are the reworked implementation of ClassManifests, so the rationale remains)
这篇关于Scala通用方法 - 没有可用于T的ClassTag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!