public
Created

Method calls & XML traversal with Scala's new Dynamic type

  • Download Gist
DynamicImpl.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
class DynamicImpl(x: AnyRef) extends Dynamic {
def _select_(name: String): DynamicImpl = {
new DynamicImpl(x.getClass.getMethod(name).invoke(x))
}
def _invoke_(name: String)(args: Any*) = {
new DynamicImpl(x.getClass.getMethod(name, args.map(_.asInstanceOf[AnyRef].getClass) : _*).invoke(x, args.map(_.asInstanceOf[AnyRef]) : _*))
}
override def typed[T] = x.asInstanceOf[T]
override def toString = "Dynamic(" + x.toString + ")"
}
 
implicit def toDynamic(x: Any): Dynamic = new DynamicImpl(x.asInstanceOf[AnyRef])
 
class Duck {
def quack = "Quack!"
}
 
class QuackingSwan {
def quack = "Swack!"
}
 
def makeQuack(d: Dynamic) {
println(d.quack.typed[String])
}
 
makeQuack(new Duck)
makeQuack(new QuackingSwan)
 
val s: Dynamic = "Hello, world!"
s.toLowerCase
s.toLowerCase.length
s.toLowerCase.length.typed[Int]
DynamicXML.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
import scala.xml.{NodeSeq, XML}
 
class DynamicXML(n: NodeSeq) extends Dynamic {
def _select_(name: String) = {
new DynamicXML(n \ name)
}
def _invoke_(name: String)(args: Any*) = {
error("unsupported")
}
override def typed[T] = n.asInstanceOf[T]
override def toString = "DynamicXML(" + n.toString + ")"
}
 
// A string, to prove I'm not cheating!
val s: String = ("""
<book>
<author>
<firstName>William</firstName>
<lastName>Shakespeare</lastName>
</author>
<title>Hamlet</title>
</book>""")
 
val book = new DynamicXML(XML.loadString(s))
 
book.author.lastName
book.title.typed[NodeSeq].text

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.