[随笔] Scala trunk中已经加入对动态类型的支持

Eastsun 2011-01-18
RT,odersky在20小时前往scala trunk中加入了一个新的类Dynamic。看过Scala Day 2010视频的童鞋应该知道,在scala中加入动态类型支持是Scala2.9or3.0的计划之一。这个类的出现表示着该计划已经进入实施阶段。
那么,这个类该如何用呢?下面是可能的用法:
scala> 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 + ")"
     | }
defined class DynamicImpl

scala> 

scala> implicit def toDynamic(x: Any): Dynamic = new DynamicImpl(x.asInstanceOf[AnyRef])
toDynamic: (x: Any)Dynamic

scala> class Duck {
     |   def quack = "Quack!"
     | }
defined class Duck

scala> class QuackingSwan {
     |   def quack = "Swack!"
     | }
defined class QuackingSwan

scala> def makeQuack(d: Dynamic) {
     |   println(d.quack.typed[String])
     | }
dynatype: d._select_("quack")
makeQuack: (d: Dynamic)Unit

scala> makeQuack(new Duck)
Quack!

scala> makeQuack(new QuackingSwan)
Swack!

scala> val s: Dynamic = "Hello, world!"
s: Dynamic = Dynamic(Hello, world!)

scala> s.toLowerCase
dynatype: line8$object.$iw.$iw.s._select_("toLowerCase")
res2: Dynamic = Dynamic(hello, world!)

scala> s.length
dynatype: line8$object.$iw.$iw.s._select_("length")
res3: Dynamic = Dynamic(13)

scala> s.isEmpty.typed[Boolean]
dynatype: line8$object.$iw.$iw.s._select_("isEmpty")
res4: Boolean = false

yangliting187 2011-01-18
rrrr
QiaoDuanni 2011-09-07

请注意. scala 2.9.1 函数已经更改为 x.applyDynamic("meth", args)

如下:

def _select_applyDynamic(name: String)(args: Any*) : DynamicImpl = ...

def _invoke_  ...

Global site tag (gtag.js) - Google Analytics