Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Protocols vs Scala Structural Types

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?
like image 921
Vasil Remeniuk Avatar asked Dec 22 '10 10:12

Vasil Remeniuk


1 Answers

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.

like image 111
James Iry Avatar answered Sep 23 '22 01:09

James Iry