我在 Clojure 中使用 deftype 时遇到问题。如果我运行以下代码:
(defprotocol TestProt
(geta [this])
(getb [this]))
(deftype TestType [a b]
TestProt
(geta [this] a)
(getb [this] b))
(defn test-function [^TestType a-testtype]
(print (.geta a-testtype)))
(def test-tt (TestType. 1 1))
(test-function test-tt)
然后编译器抛出:ClassCastException MyProject.core.TestType 无法转换为 MyProject.core.TestType。我做错了什么,还是这是一个错误?请注意,如果我从测试函数中删除类型注释,那么它只是:
(defn test-function [a-testtype]
(print (.geta a-testtype)))
然后代码工作正常,但我收到有关反射的警告(启用了 warn-on-reflect),并且运行速度较慢,这违背了在我当前用例中使用 deftype 的目的。
编辑:好的,代码在 repl 中工作,但当我使用 ctrl-alt-s 加载它时就不行了(我通过逆时针在 Eclipse 中运行它)。所以问题似乎出在 Eclipse 或逆时针方向上。
最佳答案
当您重新定义类型(使用 deftype
或 defrecord
)但在某个地方使用了先前存在的类时,就会发生这种情况,在您的情况下类型提示。
我无法使用 CountercClockwise 的 CtrlAltS 重现您所描述的行为,但它确实以新的方式评估以下表达式REPL,因此它可能会以某种方式帮助诊断您的具体情况。
(defprotocol TestProt
(geta [this])
(getb [this]))
(deftype TestType [a b]
TestProt
(geta [this] a)
(getb [this] b))
(defn test-function [^TestType a-testtype]
(print (.geta a-testtype)))
(def test-tt (TestType. 1 1))
(println :first (test-function test-tt))
;= :first 1
;; redefine the type...
(deftype TestType [a b]
TestProt
(geta [this] a)
(getb [this] b))
;; ...and the test-tt var with the new version
(def test-tt (TestType. 1 1))
(println :second (test-function test-tt))
;= ClassCastException user.TestType cannot be cast to user.TestType user/test-function (NO_SOURCE_FILE:89)
关于java - ClassCastException MyType 无法转换为 MyType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21254384/