3

I'm writing a generic method that can convert Any type argument to the an object of passed ClassTag[T] type, if possible.

def getTypedArg[T: ClassTag](any: Any): Option[T] = {
      any match {
        case t: T => Some(t)
        case invalid =>
          logger.warn(s"Invalid argument: $invalid")
          None
      }
}

I want the log message to be more precise like this:

case invalid => logger.warn(s"Invalid argument: $invalid of type $className")

How can I retrieve className from the ClassTag[T]?

Alternatively, is there a fundamentally different approach that can serve my use-case better?

y2k-shubham
  • 10,183
  • 11
  • 55
  • 131
  • I found [this related question](https://stackoverflow.com/questions/23974706/how-do-i-get-the-classof-a-classtag) but can't figure out how to apply it to my example – y2k-shubham Feb 02 '18 at 05:45

1 Answers1

2

Add this import statement

import scala.reflect._

and change the logging statement as,

logger.warn(s"Invalid argument: $invalid of type ${classTag[T].runtimeClass}")

This is taken from Scala classOf for type parameter

S.Karthik
  • 1,389
  • 9
  • 21
  • 1
    That worked; I further added `getSimpleName` to convert *qualified class-name with packages* `com.company.package.A$A45$A$A45$MyClass` to *just the class-name* `MyClass`, i.e., `classTag[T].runtimeClass.getSimpleName` – y2k-shubham Feb 02 '18 at 09:09