Last active
May 25, 2024 10:18
-
-
Save dacr/88de2aec50f51fd3939523eb77b4dfef to your computer and use it in GitHub Desktop.
Obtain the class type of a generic type at runtime / published by https://github.com/dacr/code-examples-manager #62dcc5ac-2855-454b-9350-0f9c1e98c2fb/c4395dffdeba34d1ab51f5a241be0c9237cf457d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : Obtain the class type of a generic type at runtime | |
// keywords : scala, language-feature, class, classtag, generics, reflect, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 62dcc5ac-2855-454b-9350-0f9c1e98c2fb | |
// created-on : 2022-01-22T08:18:18+01:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
// --------------------- | |
import scala.reflect.ClassTag | |
// Won't compile | |
// def checkKO[T](): Option[T] = | |
// println(classOf[T].getCanonicalName) | |
// None | |
def check[T]()(implicit tag: ClassTag[T]): Option[T] = | |
val genericTypeClass = tag.runtimeClass.asInstanceOf[Class[T]] | |
println(genericTypeClass.getCanonicalName) | |
None | |
case class Bidule(name: String) | |
check[String]() | |
check[Double]() | |
check[Bidule]() | |
check[java.awt.Image]() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment