Scala generic method - No ClassTag available for T

我们两清 提交于 2019-11-27 03:42:27
Régis Jean-Gilles

To instantiate an array in a generic context (instantiating an array of T where T is 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 ClassTag 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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!