在嵌套函数中设置一个可变字段 - deftype - clojure [英] Setting a mutable field in a nested function - deftype - clojure

查看:140
本文介绍了在嵌套函数中设置一个可变字段 - deftype - clojure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:
发布我的问题的以前版本后,我发现真正的问题是与嵌套函数。

After posting the previous version of my question I discovered that the real problem is with nested functions.

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

If I have a closure within a deftype I can not update any mutable fields from within that closure.

以下工作:

(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)导致:

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

ClassCastException user.Test可以转换为compile__stub.user.Test user.Test / fn - 152(NO_SOURCE_FILE:3

尝试运行代码时

TestInterface 代码的完整性:

(definterface TestInterface (perform [o]))


推荐答案

考虑不工作的版本,如果它的工作,将返回一个可以逃逸到野外,并从任何地方调用,设置您的不同步的本地和混乱

Consider that the version which does not work would, if it did work, return a closure which could escape into the wild and get called from wherever, setting your unsynchronized local and messing things up terribly.

如果你坚持做这样的事情,你总是可以创建一个接口,使用一个setter为你的可变字段,实现它在你的类型和调用

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

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

Direct mutation ((set! (.-x foo) ...)) won't work, since mutable fields of Clojure types (both unsynchronized and volatile) are private.

这篇关于在嵌套函数中设置一个可变字段 - deftype - clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆