Scala 中 Dynamic 类型的实际使用 [英] Practical uses of a Dynamic type in Scala
问题描述
除了与 JVM 上的动态语言集成之外,Dynamic 的其他强大用途是什么?在像 Scala 这样的静态类型语言中输入?
Besides integration with dynamic languages on the JVM, what are the other powerful uses of a Dynamic type in a statically typed language like Scala?
推荐答案
我想动态类型可用于实现 JRuby、Groovy 或其他动态 JVM 语言中的一些功能,例如动态元编程和 method_missing.
I guess a dynamic type could be used to implement several of the features found in JRuby, Groovy or other dynamic JVM languages, like dynamic metaprogramming and method_missing.
>
例如在 Rails 中创建类似于 Active Record 的动态查询,其中带有参数的方法名称在后台转换为 SQL 查询.这是使用 Ruby 中的 method_missing 功能.像这样的东西(理论上 - 没有尝试实现这样的东西):
For example creating a dynamic query similar to Active Record in Rails, where a method name with parameters is translated to an SQL query in the background. This is using the method_missing functionality in Ruby. Something like this (in theory - have not tried to implement anything like this):
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 类中明确定义它们:
Allowing usage like this, where you can call methods 'name' and 'findByName' without having them explicitly defined in the Person class:
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")
如果要添加动态元编程,则需要 Dynamic 类型以允许调用在运行时添加的方法..
If dynamic metaprogramming was to be added, the Dynamic type would be needed to allow invoking methods that have been added during runtime..
这篇关于Scala 中 Dynamic 类型的实际使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!