what is the shortest series of casts needed to get

136 views
Skip to first unread message

Lawrence Krubner

unread,
Oct 4, 2015, 9:03:21 PM10/4/15
to Clojure
My co-worker wrote an app in Java, which I call as a library within my own app. His code is expecting an ArrayList, and up until now I've been handing in an empty one like this: 

        accounts (java.util.ArrayList. 1000)
        sentence-parse-response-map (.init instance-of-sentence-parser incoming-message accounts contacts required-fields)

In my own code, I fetch the accounts and store it in a Clojure vector. Imagine something like: 

["Lisa Hare" "Morgan Aung" "Ki Xi"]

If I do this: 

(ancestors (type accounts))

I see this:

#{clojure.lang.IPersistentStack java.lang.Comparable java.lang.Iterable clojure.lang.IMeta clojure.lang.IReduceInit clojure.lang.AFn clojure.lang.Associative clojure.lang.IReduce clojure.lang.ILookup clojure.lang.IHashEq clojure.lang.Counted java.util.Collection clojure.lang.Reversible clojure.lang.IEditableCollection clojure.lang.Seqable java.io.Serializable java.lang.Runnable clojure.lang.IPersistentVector java.util.concurrent.Callable clojure.lang.IObj java.util.RandomAccess clojure.lang.Indexed clojure.lang.Sequential java.util.List java.lang.Object clojure.lang.IFn clojure.lang.IPersistentCollection clojure.lang.APersistentVector}

This: 

(ancestors java.util.ArrayList)

gives me: 

#{java.lang.Iterable java.util.AbstractList java.util.Collection java.util.AbstractCollection java.io.Serializable java.util.RandomAccess java.util.List java.lang.Object java.lang.Cloneable}

So what is the shortest path (of casts) to go from what I have to what he expects? Should I cast to  java.util.List and then call .toArray()? 




Francis Avila

unread,
Oct 4, 2015, 9:39:36 PM10/4/15
to Clojure
Does he actually need a real arraylist, or will something fulfilling a collection interface (Collection, Iterable, or List for example) be ok? Many clojure types do not require any casting at all as long as the java code writes to a collection interface and doesn't expect to be able to mutate the object. (Both of these are good Java idioms: write to interfaces not classes, and copy defensively.)

So if your coworkers code just needs something iterable (for example), you may not need to do any casting at all: just give him the vector.

If your coworker's code needs a real ArrayList and can accept no substitutes, (java.util.ArrayList. your-vector) will make an ArrayList copy of a vector's contents.

Lawrence Krubner

unread,
Oct 10, 2015, 3:45:03 PM10/10/15
to Clojure
Thank you. This was a good idea: 
Reply all
Reply to author
Forward
0 new messages