-
Notifications
You must be signed in to change notification settings - Fork 1.1k
reflect runtime class name using Quotes #11161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
this seems like a weird interaction with the empty package being special cased to print as the empty string |
I would disagree that |
@bishabosha |
The only alternative I can think of would be to have some kind of function that goes from Type[T] to ClassTag[T]. |
can you use |
That would give me an |
@bishabosha Looks like I found a workaround for this particular issue. I think I'll keep this open though because the naming seems incorrect. |
thats a great point 😂, what is the workaround? |
It is impossible to do |
What we might have is a object TypeRepr {
...
def classNameOf[T: Type](using Quotes): Option[String] = ...
}
TypeRepr.classNameOf[T] Not sure what it would return anonymous classes or any other class with a generated name. Those names might not be stable. |
Have you tried: def showTypeImpl[T: Type](using Quotes): Expr[String] = {
import quotes.reflect._
'{classOf[T].getName()}
} ? This seems to me like the most straightforward way to get that information in a reliable way. |
@sjrd No, I haven't tried that actually 🤦♂️. Thanks for suggesting! |
@deusaquilus but does your use case require inspecting the class name at compile time? |
@sjrd I was trying your suggestion in a different context but I get
Am I missing something? 🤔 |
For anyone interested, following the suggestion of @bishabosha I've workaround the initial issue by getting a |
@gaeljw That's really cool, I didn't know about |
@deusaquilus absolutely, I just tried |
The canonical solution is probably something like import scala.quoted._
import scala.reflect.ClassTag
inline def showType[T]: String = ${ showTypeImpl[T] }
private def showTypeImpl[T: Type](using Quotes): Expr[String] =
Expr.summon[ClassTag[T]] match
case Some(ct) => '{ $ct.runtimeClass.getName }
case None =>
import quotes.reflect._
report.throwError(s"Unable to find a ClassTag for type ${Type.show[T]}", Position.ofMacroExpansion) |
Is it still useful to inspect the future class name at compiletime, rather than waiting until runtime? |
Uh oh!
There was an error while loading. Please reload this page.
Minimized code
Let's say I create a simple enum type:
Then I create a macro to print it's name:
Output
Then I call it:
Expectation
This is very unexpected because if I use a ClassTag/runtime-class to print the name I get the following:
This is the same as the print-out from the runtimeClass:
I would expect the result from typeSymbol.fullName to be the same as runtimeClass.getName.
The text was updated successfully, but these errors were encountered: