Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Retrieve class-name from ClassTag

Tags:

generics

scala

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?

like image 791
y2k-shubham Avatar asked Dec 06 '25 16:12

y2k-shubham


1 Answers

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

like image 166
S.Karthik Avatar answered Dec 08 '25 10:12

S.Karthik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!