Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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?

like image 801
Alex Dean Avatar asked Oct 28 '12 15:10

Alex Dean


1 Answers

^: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.
like image 74
Joost Diepenmaat Avatar answered Nov 20 '22 07:11

Joost Diepenmaat