除了在JVM上与动态语言集成之外,在诸如Scala之类的静态类型语言中Dynamic type的其他强大功能是什么?

最佳答案

我猜动态类型可以用来实现JRuby,Groovy或其他动态JVM语言中的一些功能,例如动态元编程和method_missing。

例如,创建类似于Rails中Active Record的动态查询,其中带有参数的方法名称在后台转换为SQL查询。这是在Ruby中使用method_missing功能。这样的事情(理论上-尚未尝试实现这样的事情):

class Person(val id: Int) extends Dynamic {
  def _select_(name: String) = {
    val sql = "select " + name + " from Person where id = " id;
    // run sql and return result
  }

  def _invoke_(name: String)(args: Any*) = {
    val Pattern = "(findBy[a-zA-Z])".r
    val sql = name match {
      case Pattern(col) => "select * from Person where " + col + "='" args(0) + "'"
      case ...
    }
    // run sql and return result
  }
}

允许这样的用法,在其中您可以调用方法“name”和“findByName”,而无需在Person类中明确定义它们:
val person = new Person(1)

// select name from Person where id = 1
val name = person.name

// select * from Person where name = 'Bob'
val person2 = person.findByName("Bob")

如果要添加动态元编程,则需要动态类型以允许调用在运行时添加的方法。

关于scala - Scala中Dynamic类型的实际使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4709183/

10-14 19:06
查看更多