Created
December 2, 2012 22:35
-
-
Save travisbrown/4191360 to your computer and use it in GitHub Desktop.
Scala 2.10 macro varargs examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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