Scala 中动态类型的实际使用
除了与 JVM 上的动态语言集成之外,动态类型还有哪些其他强大用途 使用像 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜想动态类型可以用来实现 JRuby、Groovy 或其他动态 JVM 语言中的一些功能,例如动态元编程和 method_missing。
例如,创建类似于 Rails 中的 Active Record 的动态查询,其中带参数的方法名称在后台转换为 SQL 查询。这是使用 Ruby 中的 method_missing 功能。像这样的东西(理论上 - 没有尝试实现类似的东西):
允许这样的使用,您可以调用方法“name”和“findByName”,而无需在 Person 类中显式定义它们:
如果动态元编程是添加后,需要动态类型来允许调用在运行时添加的方法。
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):
Allowing usage like this, where you can call methods 'name' and 'findByName' without having them explicitly defined in the Person class:
If dynamic metaprogramming was to be added, the Dynamic type would be needed to allow invoking methods that have been added during runtime..
Odersky 表示,主要动机是与动态语言集成:http://groups.google。 com/group/scala-language/msg/884e7f9a5351c549
[编辑] Martin 进一步证实了这一点 此处
Odersky says the primary motivation was integration with dynamic languages: http://groups.google.com/group/scala-language/msg/884e7f9a5351c549
[edit] Martin further confirms this here
您还可以将它用作地图上的语法糖:
说实话,这只会为您节省几次击键:
You might also use it for syntactic sugar on maps:
To be honest this only saves you a couple of keystrokes from: