Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created February 24, 2012 12:32
Show Gist options
  • Save xuwei-k/1900672 to your computer and use it in GitHub Desktop.
Save xuwei-k/1900672 to your computer and use it in GitHub Desktop.
not var macro scala
def macro NotVar(c:Any) = {
import reflect.api.Modifier.mutable
(new Transformer{
override def transform(tree:Tree):Tree = tree match{
case ValDef(m,_,_,_) if m.hasModifier(mutable) => sys.error("can't use var !!!")
case _ => super.transform(tree)
}
}).transform(c)
}
$ scala -Xmacros
Welcome to Scala version 2.10.0-M2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_29).
Type in expressions to have them evaluated.
Type :help for more information.
scala> def macro NotVar(c:Any) = {
| import reflect.api.Modifier.mutable
| (new Transformer{
| override def transform(tree:Tree):Tree = tree match{
| case ValDef(m,_,_,_) if m.hasModifier(mutable) => sys.error("can't use var !!!")
| case _ => super.transform(tree)
| }
| }).transform(c)
| }
NotVar: (c: Any)Any
scala> NotVar({val a = 1 ; a })
res0: Int = 1
scala> NotVar({var b = 2 ; b })
<console>:9: error: exception during macro expansion: can't use var !!!
NotVar({var b = 2 ; b })
^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment