showCode
showCode
Scala 2.11からshowCode
というすごいmethodが追加されており、
これは「コンパイル可能な文字列を返す」ということで、
c.Tree
とString
が相互に変換可能になっている。
object Parse { def apply(x: String): Any = macro Impl.apply final class Impl(val c: Context) { import c.universe._ def apply(x: c.Tree): c.Tree = c.parse { x match { case q"${y: String}" => y } } } } object Unparse { def apply(x: Any): String = macro Impl.apply final class Impl(val c: Context) { import c.universe._ def apply(x: c.Tree): c.Tree = { q"${showCode(x)}" } } }
これでc.Tree
を文字列リテラルとして扱えてしまう。
注意点
2.11.1時点では型パラメータがサポートされていない(すぐ直るようである)。