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

452 views Asked by At

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?

3

There are 3 answers

0
Alex Taggart On BEST ANSWER

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]
0
Shlomi On

Simply construct a String object with that byte array:

(println (String. byte-arr))
2
Chiron On

I don't recommend to override toString. It is too much global change and you might break some thing that relays on the default behaviour.

Why not creating a function for your specific requirement?