Search code examples
scala

The difference usages of scala.reflect.classTag


I am new to Scala and I saw there are two usages for retrieving the classTags in the codebase. Can I say below two usages (stringClassTag v.s stringClassTag2) are equivalent? thank you.

import scala.reflect.{classTag, ClassTag}

val stringClassTag: ClassTag[String] = implicitly[ClassTag[String]]

val stringClassTag2: ClassTag[String] = classTag[String]


Solution

  • Yes, they are identical.

    If you look at the definition of classTag:

    def classTag[T](implicit ctag: ClassTag[T]) = ctag
    

    And implicitly:

    @inline def implicitly[T](implicit e: T): T = e
    

    implicitly is a generic method to "summon" an implicit value of any type T, classTag does the same but only for ClassTag[T] types.