Friday, 15 March 2013

macros - Scala: Get type name without runtime reflection and without type instance -


I want to get a type of name, as a string, without runtime reflection.

Using a macro, and with an example of type, I can do it like this:

  def typeNameFromInstance [A] (example: A): string = macro typeNameFromInstanceImplementation [A] Def typeNameFromInstanceImplementation [A] (c: context) (Example: c.Expr [a]): c.Expr [string] = {import c.universe. _Value name = instance.actualType.toString c. XPR [String] (Little (Constant (name))}   

How can I do without this type of example? I like the signature of a function:

  DF type name [A]: string   

I can not use class tags because they do not have full type of name I just can not use a typewriter.

Edit: It appears that This is not possible in full generality (for example, nested function calls). This comment has been given in the acceptable answer given below.

You can use a tree that represents the macro app: c.macroApplication

  def typeName [T]: string = macro typeName_impl [t] def typeName_impl [T] (c: context): c.Expr [string] = {import c.universe._ Val TypeApply (_, list (typeTree)) = c.macroApplication c.literal ( TypeTree.toString () }   

Edit:

There is another way to get one, but maybe a little better:

  def typeName [T]: string = macro typeName_impl [t] def typeName_impl [t: c .WeakTypeTag] (c: context): c.Expr [string] = {import c.universe._ c .literal (weakTypeOf [T] .toString ())}    

No comments:

Post a Comment