Frage

Context has methods literal(Int), literal(String), etc. How can I create a literal symbol given the name (i.e. 'name)? There is an obvious workaround: create Symbol.apply(literal(name)) instead, but I expect there should be a direct method as well.

War es hilfreich?

Lösung

Is q"'sym" too obvious?

c.Expr[Any](q"'mysym")

By obvious, I mean, sorry if this is obviously not what you mean.

Less conveniently,

c.Expr[Any](c.parse("'asym"))

c.Expr[Any](c.parse(s"'$name"))

or maybe painfully,

c.Expr[Any](Apply(c.typeOf[scala.Symbol].typeSymbol, c.literal("mysym").tree))

Andere Tipps

In soon to be realeased 2.11 you'll be able to just unquote symbol into a quasiquote to get a correct tree without hassle:

val s: scala.Symbol = 'foo
q"$s" // q"'foo"

This should work in 2.10 with macro paradise plugin as well.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top