Clojure协议与Scala结构类型 [英] Clojure Protocols vs Scala Structural Types

查看:214
本文介绍了Clojure协议与Scala结构类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rich Hickey的采访后://clojure.org/protocolsrel =nofollow>协议在Clojure 1.2中,并且对Clojure了解甚少,我有一些关于Clojure协议的问题:




  • 是否打算执行与结构类型在Scala中?协议对结构类型(性能,灵活性,代码清晰度等)有什么好处?

  • 与Scala的互操作性问题:在Scala中可以使用协议而不是结构类型吗?


解决方案

p>完全无关。



Scala是一种静态类型语言。 Clojure是一种动态类型语言。这种差异从根本上塑造了它们。



结构类型是静态类型,周期。它们只是一种让编译器静态地证明对象将具有特定结构的方法(我说这里证明了,但是转换可以总是引起伪造的证明)。



Clojure中的协议是一种创建动态调度的方法,它比反射或在地图中查找更快。在语义上,他们并不真正地扩展Clojure的功能,但在操作上,它们明显比之前使用的机制更快。



Scala traits更接近协议,也是Java接口,但同样有一个静态vs动态问题。 Scala traits必须在编译时与类关联,类似于Java接口。 Clojure协议可以在事件之后在运行时被添加到数据类型,甚至由第三方。



类似Clojure协议在Java和Scala中可以通过像包装器/代理模式或动态代理(http://download.oracle.com/javase/1.4.2/docs/guide/reflection/proxy.html )。但是,这些将是一个很笨拙的比Clojure协议和获得对象身份权利也是棘手的。


After watching the interview with Rich Hickey on Protocols in Clojure 1.2, and knowing very little about Clojure, I have some questions on Clojure Protocols:

  • Are they intended to do the same thing as Structural Types in Scala? What benefits do Protocols have over Structural Types (performance, flexibility, code clarity, etc.)? Are they implemented through reflections?
  • Questions on interoperability with Scala: Can Protocols be used instead of Structural Types in Scala? Can they be extended (if 'extension' term can be applied to Protocols) in Scala?

解决方案

Totally unrelated.

Scala is a statically typed language. Clojure is a dynamically typed language. This difference shapes both of them fundamentally.

Structural types are static types, period. They're just a way to have the compiler prove statically that an object will have a particular structure (I say prove here, but casting can cause bogus proofs as always).

Protocols in Clojure are a way to create dynamic dispatch that is much faster than reflection or looking things up in a map. In a semantic sense they don't really extend the capabilities of Clojure, but operationally they are significantly faster than the mechanisms used before.

Scala traits are a bit closer to protocols, as are Java interfaces, but again there's a static vs dynamic issue. Scala traits must be associated with a class at compile time, similar to Java interfaces. Clojure protocols can be added to a datatype at runtime after the fact even by a third party.

Something like Clojure protocols is possible in Java and Scala through mechanisms like wrapper/proxy patterns or dynamic proxies ( http://download.oracle.com/javase/1.4.2/docs/guide/reflection/proxy.html ). But those will be a heck of a lot clumsier than Clojure protocols and getting object identity right is tricky as well.

这篇关于Clojure协议与Scala结构类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆