Skip to content

Instantly share code, notes, and snippets.

@paulp
Created May 4, 2012 01:17
Show Gist options
  • Save paulp/2590931 to your computer and use it in GitHub Desktop.
Save paulp/2590931 to your computer and use it in GitHub Desktop.
Welcome to Scala version 2.10.0-20120503-160535-58f6a13460 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_31).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
trait DynamicThis[+T] extends Dynamic {
this: T =>
def dynamicMissingMethod(which: String, method: String)(args: Any*): Any
private def wrap(which: String, method: String)(args: Any*): this.type = {
dynamicMissingMethod(which, method)(args: _*)
this
}
def selectDynamic(method: String): T = wrap("selectDynamic", method)()
def applyDynamic(method: String)(args: Any*): T = wrap("applyDynamic", method)(args: _*)
def applyDynamicNamed(method: String)(args: (String, Any)*): T = wrap("applyDynamicNamed", method)(args: _*)
def updateDynamic(method: String)(args: Any*): T = wrap("updateDynamic", method)(args: _*)
}
class Accumulator extends DynamicThis[Accumulator] {
private var calls: List[String] = Nil
def dynamicMissingMethod(which: String, method: String)(args: Any*) = calls ::= (which match {
case "selectDynamic" => method
case "applyDynamic" => args.mkString(method + "(", ", ", ")")
case "applyDynamicNamed" => args.map({ case (k, v) => k + " = " + v }).mkString(method + "(", ", ", ")")
case "updateDynamic" => "update (?) "+ args.mkString(method + "(", ", ", ")")
})
override def toString = calls.reverse mkString "."
}
// Exiting paste mode, now interpreting.
defined trait DynamicThis
defined class Accumulator
scala> val x = new Accumulator
x: Accumulator =
scala> x.bippy("hi", "mom").bingo.bong.bong.bong.and(dog = "groucho", cat = "harpo")
res0: Accumulator = bippy(hi, mom).bingo.bong.bong.bong.and(dog = groucho, cat = harpo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment