Last active
February 3, 2026 20:21
-
-
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/2f3ac764d1f5a29421d70a334aa3363d2d17f06e
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 License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // 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