Subtle array issue

11 views
Skip to first unread message

Toralf Wittner

unread,
Mar 30, 2008, 4:09:13 PM3/30/08
to Clojure
I have a small problem with arrays and Java methods. For instance

(. (new StringBuilder) (append (make-array (. Character TYPE) 3)))

will return something like "[C@76db09" instead of "". Since make-array
creates arrays via java.lang.reflect.Array.newInstance() which has
return type Object, StringBuilder.append(Object) will be invoked instead
of StringBuilder.append(char[]).

Now AFAIK there is no way to cast to native arrays in Clojure. In this
particular case there is a workaround: (. (new StringBuilder) (append
(new String (make-array (. Character TYPE) 3)))) but I am not sure about
the general case. [1]

Would it be good to be able to cast to native arrays in Clojure to help
with Java method invocation? E.g. something like (. (new StringBuilder)
(append (. test.Test (toCharArray a)))) where 'a' is (make-array (.
Character TYPE) 3) and test.Test.toCharArray casts Object to char[]
helps in the given example.

- Toralf


-----------------------
[1] Interestingly this workaround would not pass javac if written in
Java as there is no String(Object) constructor.


Rich Hickey

unread,
Mar 30, 2008, 5:11:58 PM3/30/08
to Clojure


On Mar 30, 4:09 pm, Toralf Wittner <toralf.witt...@gmail.com> wrote:
> I have a small problem with arrays and Java methods. For instance
>
> (. (new StringBuilder) (append (make-array (. Character TYPE) 3)))
>
> will return something like "[C@76db09" instead of "". Since make-array
> creates arrays via java.lang.reflect.Array.newInstance() which has
> return type Object, StringBuilder.append(Object) will be invoked instead
> of StringBuilder.append(char[]).
>
> Now AFAIK there is no way to cast to native arrays in Clojure. In this
> particular case there is a workaround: (. (new StringBuilder) (append
> (new String (make-array (. Character TYPE) 3)))) but I am not sure about
> the general case. [1]
>
> Would it be good to be able to cast to native arrays in Clojure to help
> with Java method invocation? E.g. something like (. (new StringBuilder)
> (append (. test.Test (toCharArray a)))) where 'a' is (make-array (.
> Character TYPE) 3) and test.Test.toCharArray casts Object to char[]
> helps in the given example.
>

You should be able to type-hint arrays using strings and the JVM array
name syntax (see the docs for Class.getName):

(. (new StringBuilder) (append #^"[C" (make-array (. Character TYPE)
3)))

Rich

Toralf

unread,
Mar 30, 2008, 5:20:03 PM3/30/08
to Clojure
On Mar 30, 11:11 pm, Rich Hickey <richhic...@gmail.com> wrote:
> You should be able to type-hint arrays using strings and the JVM array
> name syntax (see the docs for Class.getName):
>
> (. (new StringBuilder) (append #^"[C" (make-array (. Character TYPE)
> 3)))
>
> Rich

Yes, this works - thanks!

- Toralf
Reply all
Reply to author
Forward
0 new messages