public
Last active

Scala 2.10 macro varargs examples

  • Download Gist
macro-varargs.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/**
* Related to this question: http://stackoverflow.com/q/13663216/334519
*
* Unhelpful error message:
* scala> MacroExample.foo(List(1, 2, 3): _*)
* <console>:8: error: no `: _*' annotation allowed here
* (such annotations are only allowed in arguments to *-parameters)
* MacroExample.foo(List(1, 2, 3): _*)
* ^
*
* And downright strange:
* scala> MacroExample.bar(List(1, 2, 3): _*)
* res0: List[Int] = List(1, 2, 3)
*
* scala> MacroExample.bar(1, 2, 3)
* res1: Int = 1
**/
 
import language.experimental.macros
import scala.reflect.macros.Context
 
object MacroExample {
def foo(xs: Int*): Any = macro foo_impl
def foo_impl(c: Context)(xs: c.Expr[Int]*) = xs.head
 
def bar(xs: Int*): Any = macro bar_impl
def bar_impl(c: Context)(xs: c.Expr[Int]*) = {
import c.universe._
 
xs.head.tree match {
case Typed(e, _) => c.Expr(e)
case i => c.Expr(i)
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.