I’m trying out Clojure 1.2, specifically mutable fields which are supported in deftype according to the clojure.org documentation.
But I can’t get the set to work. What is the syntax for updating a field? Or isn’t mutability implemented yet?
(definterface IPoint
(getX [])
(setX [v]))
(deftype Point [x]
IPoint
(getX [this] x)
(setX [this v] (set! (.x this) v)))
user=> (def p (Point. 10))
user=> (.getX p)
10
user=> (.setX p 20)
ClassCastException: user.Point cannot be cast to compile__stub.user.Point
Using a 1.2 snapshot from a few days ago.
deftype‘s default is still to have the fields be immutable; to override this, you need to annotate the names of the fields which are to be mutable with appropriate metadata. Also, the syntax forset!of instance fields is different. An example implementation to make the above work:There’s also
:unsynchronized-mutable. The difference is as the names would suggest to an experienced Java developer. 😉 Note that providing either annotation has the additional effect of making the field private, so that direct field access is no longer possible:Also, 1.2 will likely support the syntax
^:volatile-mutable xas shorthand for^{:volatile-mutable true} x(this is already available on some of the new numerics branches).Both options are mentioned in
(doc deftype); the relevant part follows — mind the admonition!