我正在优化应用程序的一个以性能为中心的小部分。我正在尝试创建一个通过 deftype
(deftype MyThing [foo bar baz])
但是,我似乎找不到任何有关如何键入提示这些数组的文档,并且如果没有类型提示,就会发生反射。
(def my-array (make-array MyThing 10))
(aget my-array 0)
给出警告:
Reflection warning, call to static method aget on clojure.lang.RT can't be resolved (argument types: core.MyThing, int).
有没有办法正确提示类型?
最佳答案
我很惊讶在 Stack Overflow 上没有找到任何关于这个主题的问题,更惊讶的是添加类型提示的官方文档没有涵盖这一点 - 我确信我能够将其关闭为重复,或链接到官方文档,但在这里我像野蛮人一样用手输入它。
类型提示的“原始”版本,其他形式只是简写1,是
^"Foo" xs
其中 Foo 是您要提示的类的 JVM 内部名称。原始数组 (^ints xs
) 和普通类类型 (^MyType x
) 都有简写,但这不包括非原始类型的数组。为此,您必须知道您的类型的官方类名称。您可以查找相关规则,但最简单的方法就是询问口译员!
user=> (defrecord Foo [])
user.Foo
user=> (def foos (make-array Foo 10))
#'user/foos
user=> (class foos)
[Luser.Foo;
user=> (aget foos 0)
Reflection warning, null:1:1 - call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).
nil
user=> (aget ^"[Luser.Foo;" foos 0)
nil
1 实际上,更原始的是 ^{:tag "Foo"}
,但这种区别对于这个问题并不重要。
关于clojure - 是否可以输入提示填充有 deftype 对象的 Clojure 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59450366/