编辑: 在发布我的问题的先前版本后,我发现真正的问题在于嵌套函数。
如果我在 deftype
中有一个闭包,我无法更新该闭包内的任何可变字段。
例如以下作品:
(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]))
最佳答案
考虑一下,如果不起作用的版本确实起作用,则会返回一个闭包,该闭包可能会逃逸到野外并从任何地方调用,从而设置不同步的本地并将事情搞得一团糟。
如果您坚持做这种事情,您始终可以为可变字段创建一个带有 setter 的接口(interface),在您的类型中实现它,并在需要设置此字段的任何地方调用 setter。
直接突变 ((set! (.-x foo) ...)
) 不起作用,因为 Clojure 类型的可变字段(不同步和易失)是私有(private)的。
关于clojure - 在嵌套函数中设置可变字段 - deftype - clojure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18236241/