Created
January 17, 2011 20:16
-
-
Save jorgeortiz85/783394 to your computer and use it in GitHub Desktop.
Method calls & XML traversal with Scala's new Dynamic type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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