Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Created December 2, 2012 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travisbrown/4191360 to your computer and use it in GitHub Desktop.
Save travisbrown/4191360 to your computer and use it in GitHub Desktop.
Scala 2.10 macro varargs examples
/**
* 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)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment