Scala generic method - No ClassTag available for T

ScalaGenericsScala 2.10

Scala Problem Overview


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.

Scala Solutions


Solution 1 - Scala

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:

https://docs.scala-lang.org/sips/scala-2-8-arrays.html

(To put it shortly, ClassTags are the reworked implementation of ClassManifests, so the rationale remains)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChuckView Question on Stackoverflow
Solution 1 - ScalaRégis Jean-GillesView Answer on Stackoverflow