Search code examples
clojureoverridingclojure-java-interop

Is it possible to override .toString for a typed Java-Array in Clojure?


I have a Byte-Array like so:

(def byte-arr (byte-array (map byte "This is a test"))) ; => #<byte[] [B@63465272>

When calling .toString I get [B@1b96107b. Is it possible to override the .toString-Method of the clojure type [B to get This is a test instead, in that case?


Solution

  • It's a bad idea to globally assume all byte arrays are a printable strings, thus the advice to just use the String constructor is correct. That said, you can add new printing globally by type.

    Printing functions eventually devolve to invocations of either print-method or print-dup multimethods, depending on whether *print-dup* is true. You can add a new method to print-method as follows using the print-sequential helper function in core_print.clj:

    (in-ns 'clojure.core)
    
    (def ^:private ByteArray (type (byte-array 0)))
    
    (defmethod print-method ByteArray [ba ^Writer w]
      (print-sequential "[" pr-on " " "]" ba w))
    

    Note this just prints a byte array as if it were a vector of bytes:

    clojure.core=> (in-ns 'user)
    #<Namespace user>
    user=> (byte-array (map byte "This is a test"))
    [84 104 105 115 32 105 115 32 97 32 116 101 115 116]