问题
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)
I've confirmed this happens in my app as well, so it's not just a REPL issue.
What am I missing?
回答1:
^: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.
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.
来源:https://stackoverflow.com/questions/13109958/why-cant-i-use-clojures-const-with-a-java-byte-array