Why can't I use Clojure's :^const with a Java byte array?

只谈情不闲聊 提交于 2019-12-23 07:36:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!