Skip to content

@jorgeortiz85 /DynamicImpl.scala
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Method calls & XML traversal with Scala's new Dynamic type
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]
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.