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

标签 clojure mutable deftype

编辑: 在发布我的问题的先前版本后,我发现真正的问题在于嵌套函数。

如果我在 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/

相关文章:

clojure - 传递给Clojure函数的参数数量错误

clojure - s/multi-spec 中的 retag 参数是什么意思?

vector - 嵌套数据结构的 Rust 可变性

clojure - 我应该什么时候在 Clojure 中使用 deftype?

xml - 使用 clojure.xml/parse 和 clojure.xml/emit 在 Clojure 中往返 xml

f# - 可变状态和观察者模式

data-structures - 可变 Haskell 堆的类型签名

servlets - 如何定义实现 servlet 接口(interface)的 clojure 类型?

clojure - 在 Clojure 中相互引用 deftypes

map - clojure 中的双向映射?