Setting a mutable field in a nested function - deftype - clojure
Asked Answered
C

1

2

EDIT: After posting the previous version of my question I discovered that the real problem is with nested functions.

If I have a closure within a deftype I can not update any mutable fields from within that closure.

E.g. the following works:

(deftype Test [^:unsynchronized-mutable x]
    TestInterface
    (perform [this o] (set! x o)))

but this does not:

(deftype Test [^:unsynchronized-mutable x]
    TestInterface
    (perform [this o] (fn [] (set! x o)) nil)) ; throws a compiler error about assigning to non-mutable field

Is there any way to reach up and access the field? Doing (set! (.x this) o) results in:

ClassCastException user.Test cannot be cast to compile__stub.user.Test user.Test/fn--152 (NO_SOURCE_FILE:3

When trying to run the code.


Code for TestInterface for completeness:

(definterface TestInterface (perform [o]))
Commercialize answered 14/8, 2013 at 15:41 Comment(4)
could you include TestInterface so I can run the example?Abroad
@ArthurUlfeldt I've updated the question and added TestInterface.Commercialize
This looks like a bug? what version of clojure?Abroad
clojure version 1.5.1Commercialize
A
3

Consider that the version which does not work would, if it did work, return a closure which could escape into the wild and get called from wherever, setting your unsynchronized local and messing things up terribly.

If you insist on doing this sort of thing, you can always create an interface with a setter for your mutable field, implement it in your type and call the setter wherever you need to set this field.

Direct mutation ((set! (.-x foo) ...)) won't work, since mutable fields of Clojure types (both unsynchronized and volatile) are private.

Apocope answered 14/8, 2013 at 21:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.