Skip to content

Instantly share code, notes, and snippets.

@retronym
Created March 1, 2012 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retronym/1952851 to your computer and use it in GitHub Desktop.
Save retronym/1952851 to your computer and use it in GitHub Desktop.
Macro types for the impatient
~/code/scala build/quick/bin/scala -Xexperimental -Xmacros
Welcome to Scala version 2.10.0-M2-0045-g4573e06a27-2012-02-25 (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> val methods = Set("foo", "bar")
methods: scala.collection.immutable.Set[String] = Set(foo, bar)
scala> object Dyno extends Dynamic {
def macro applyDynamic(mn: String)(args: Any*) = mn match {
case Literal(Constant(x: String)) if methods(x) =>
Literal(Constant(true))
case _ => sys.error("no dice")
}
}
defined module Dyno
scala> Dyno.foo
dynatype: $line2.$read.$iw.$iw.Dyno.applyDynamic("foo")()
res0: Boolean = true
scala> Dyno.bar
dynatype: $line2.$read.$iw.$iw.Dyno.applyDynamic("bar")()
res1: Boolean = true
scala> Dyno.baz
dynatype: $line2.$read.$iw.$iw.Dyno.applyDynamic("baz")()
error: exception during macro expansion: no dice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment