Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible for protocols to introduce new state into existing classes?

Tags:

clojure

I understand how protocols can be used to introduce new behaviour to existing classes, but is it possible for them (or any other Clojure mechanism) to introduce state to existing classes? More specifically, I would like to be able to associate a map with instances of a class that comes from a 3rd-party library.

like image 703
Stathis Sideris Avatar asked Apr 19 '11 16:04

Stathis Sideris


2 Answers

Protocols are conceptually similar in Java Interfaces in that they don't concern themselves with state or representation at all, so I'm pretty sure you can't do it that way unless you store the state outside the object itself. You can however use the various other ways of extending (subclassing) classes in Clojure to do this, e.g. using a proxy or with gen-class. (see http://clojure.org/java_interop#Java%20Interop-Implementing%20Interfaces%20and%20Extending%20Classes)

like image 52
pmdj Avatar answered Sep 30 '22 19:09

pmdj


You can create a protocol with set-state and get-state functions. Then extend them to the classes you want, with an implementation built around a hashmap of some kind. You can't store the state in the foreign objects, but you can have your functions share a ref of a hashtable keyed by object. I think this solution may have a number of problems, like how do you detect when an object will be GCed and its state needs to be cleared as well? You can use a WeakReference or something, but it isn't trivial.

like image 24
amalloy Avatar answered Sep 30 '22 19:09

amalloy