Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active January 31, 2023 12:52
Show Gist options
  • Save frgomes/f66e6f7d13bdaeef5a262b0ffbe7d890 to your computer and use it in GitHub Desktop.
Save frgomes/f66e6f7d13bdaeef5a262b0ffbe7d890 to your computer and use it in GitHub Desktop.
Scala: obtain ClassTag from TypeTag
import reflect.runtime.universe._
import reflect.ClassTag
def typeTag2ClassTag[T: TypeTag]: ClassTag[T] = {
ClassTag[T]( typeTag[T].mirror.runtimeClass( typeTag[T].tpe ) )
}
@frgomes
Copy link
Author

frgomes commented Jan 31, 2023

class Example {

  /** This example is not meant to do anything useful, just demonstrate the syntax */
  def example[T : Typetag](data: Any): T= {
    implicit val tag: ClassTag[T] = typeTag2ClassTag[T] 
    tag.runtimeClass switch { // you need stable identifiers here
      case String_ => data.asInstanceOf[T]
      case Int_ => data.asInstanceOf[T]
      case Long_ => data.asInstanceOf[T]
    }
  }
}
object Example {
  // declares stable identifiers
  val String_ = classOf[String]
  val Int_    = classOf[Int]
  val Long_   = classOf[Long]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment