【问题标题】:Why can't I use Clojure's :^const with a Java byte array?为什么我不能将 Clojure 的 :^const 与 Java 字节数组一起使用?
【发布时间】:2012-10-28 15:05:07
【问题描述】:

lein repl 与 Clojure 1.4.0 一起使用,我可以定义 Java 字节数组的 ^:const,但我不能用它做任何事情:

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 问题。

我错过了什么?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    ^:const 形式在编译时评估,但在 clojure 中,编译时值必须是可打印和可读的(由 clojure 阅读器)*。像大多数 java 对象一样,字节数组是不可打印或不可读取的,因此您不能将它们设为常量。

    此外,根据文档,^:const 仅对原语有用。不是原始数组。

    【讨论】:

    • 谢谢 Joost,这很有启发性!
    • 我来自非 Java 背景,今天早上我花了一段时间来解决这个问题,我的值是 java.io.File。这个问题和答案有助于理解我意识到发生了什么的“为什么”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2013-07-02
    • 2015-11-08
    • 2013-08-24
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多