问题描述
使用Clojure 1.4.0中的 lein repl
,我可以定义一个Java字节数组的 ^:const
,但我不能对它做任何事情:
Using lein repl
with Clojure 1.4.0, I can define a ^:const
of a Java byte array, but I can't then do anything with it:
user=> (def x (byte-array (map byte [0 1 2 3])))
#'user/x
user=> (alength x)
4
user=> (type x)
[B
user=> (def ^:const cx (byte-array (map byte [0 1 2 3])))
#'user/cx
user=> (alength cx)
CompilerException java.lang.RuntimeException: Can't embed object in code, maybe print-dup not defined: [B@10e6cbd, compiling:(NO_SOURCE_PATH:1)
user=> (type cx)
CompilerException java.lang.RuntimeException: Can't embed object in code, maybe print-dup not defined: [B@10e6cbd, compiling:(NO_SOURCE_PATH:1)
我已经确认这发生在我的应用程序,所以它不只是一个REPL问题。
I've confirmed this happens in my app as well, so it's not just a REPL issue.
我缺少什么?
推荐答案
^:const形式在编译时被评估,但是在clojure中,编译时值必须是可打印和可读的(由clojure读取器)*。像大多数java对象一样,字节数组是不可打印的或可读的,所以你不能在它们之间创建一个常量。
^:const forms are evaluated at compile time, but in clojure, compile-time values have to be printable and readable (by the clojure reader)*. Like most java objects, byte-arrays aren't printable or readable, so you can't make a constant out of them.
另外,根据文档, :const只对原语有用。不是原始数组。
Also, according to the docs, ^:const is only useful for primitives. not primitive arrays.
- 另请参见了解相关问题。
- See also http://www.infoq.com/presentations/Clojure-Macros for some related issues.
这篇关于为什么我不能使用Clojure的:^ const与Java字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!