mercredi 25 février 2015

Scala: get param default value: can't access `apply$default$i` inside companion object

I'm writing a macro that needs to get the default value of a constructor parameter. This answer shows this can be done by accessing the compiler-generated method apply$default$i on the companion object, where apply is the constructor's name and i is the 1-based parameter index.


However, this doesn't work if the macro is called from inside the companion object itself. Presumably the typechecking of the code in the companion object happens before the compiler generates the apply$default$i method.


This code works (whether written manually or generated by the macro):



case class C(i: Int = 1)
object C
def x: Int = C.apply$default$1


But this doesn't:



case class C(i: Int = 1)
object C {
def x: Int = C.apply$default$1
}


scalac complains that value apply$default$1 is not a member of object C.


I need to call the macro from the companion object because the macro defines an implicit typeclass instance.


I could generate code that will, at runtime, use reflection to access the apply$default$i method. But this is inelegant. If I know the compiler is going to generate a certain method, how can I access it in compiled code?






Aucun commentaire:

Enregistrer un commentaire