Setting a mutable field in a nested function - deftype - clojure

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

If I have a closure inside deftype , I cannot update any mutable fields from this closure.

eg. following works:

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

but this is not so:

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

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

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

When trying to run code.


Code for TestInterface for completeness:

 (definterface TestInterface (perform [o])) 
+2
source share
1 answer

Keep in mind that a version that doesnโ€™t work will return a closure that could escape into the wild and receive a call from anywhere, making it very difficult to configure your unsynchronized local and messy things.

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

A direct mutation ( (set! (.-x foo) ...) ) will not work, since mutable fields of Clojure types (both unsynchronized and unstable) are private.

+2
source

Source: https://habr.com/ru/post/987973/


All Articles