在嵌套函数中设置可变字段 - deftype - clojure

时间:2013-08-14 15:41:37

标签: clojure mutable deftype

修改 在发布我的问题的先前版本后,我发现真正的问题是嵌套函数。

如果我在deftype内有一个闭包,我无法更新该闭包内的任何可变字段。

E.g。以下作品:

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

但这不是:

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

有没有办法到达并进入该领域?执行(set! (.x this) o)会导致:

ClassCastException user.Test无法强制转换为compile__stub.user.Test user.Test / fn - 152(NO_SOURCE_FILE:3

尝试运行代码时。


完整性TestInterface的代码:

(definterface TestInterface (perform [o]))

1 个答案:

答案 0 :(得分:2)

考虑到不起作用的版本,如果它确实有效,将返回一个闭包,它可以逃到野外并从任何地方调用,设置你的非同步本地和搞乱的东西。

如果你坚持做这类事情,你总是可以为你的可变字段创建一个带有setter的界面,在你的类型中实现它,并在你需要设置这个字段的地方调用setter。

直接变异((set! (.-x foo) ...))不起作用,因为Clojure类型的可变字段(非同步和易失性)都是私有的。