Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Practical uses of a Dynamic type in 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?

question from:https://stackoverflow.com/questions/4709183/practical-uses-of-a-dynamic-type-in-scala

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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
  }
}

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")

If dynamic metaprogramming was to be added, the Dynamic type would be needed to allow invoking methods that have been added during runtime..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...