scalaimplicitclasstag

How are ClassTags made available in Scala?


With

def fn[T: ClassTag](...)

there needs to be an implicit ClassTag[T] available. How are these made available? Is there a list somewhere of ClassTags? I see an implicit val c: ClassTag[Any] wouldn't cut it as ClassTag is nonvariant. And how are ClassTags made available for custom classes? For example, in

import scala.reflect.ClassTag
class A
def fn[T: ClassTag](e: T) = Array.fill[T](1)(e)
fn(new A())

where is ClassTag[A] coming from? This code compiles without me defining one.

Searching for implicits in Predef and the reflection package in the source code didn't help me.


Solution

  • The answer is in the documentation for the class:

    If an implicit value of type u.ClassTag[T] is required, the compiler will make one up on demand.