【问题标题】:Setting a mutable field in a nested function - deftype - clojure在嵌套函数中设置可变字段 - deftype - clojure
【发布时间】:2013-08-14 15:41:36
【问题描述】:

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

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

【问题讨论】:

  • 能否包含 TestInterface 以便我运行示例?
  • @ArthurUlfeldt 我已经更新了问题并添加了 TestInterface。
  • 这看起来像一个错误?什么版本的clojure?
  • clojure 版本 1.5.1

标签: clojure mutable deftype


【解决方案1】:

考虑不工作的版本,如果它工作,返回一个可以逃到野外并从任何地方被调用的闭包,设置你不同步的本地并且把事情搞得一团糟。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多