This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2021-10-05
Channels
- # beginners (46)
- # calva (89)
- # cider (24)
- # clara (7)
- # clj-kondo (36)
- # clojure (33)
- # clojure-australia (4)
- # clojure-dev (9)
- # clojure-europe (15)
- # clojure-israel (1)
- # clojure-nl (1)
- # clojure-uk (13)
- # clojurescript (55)
- # community-development (38)
- # conjure (1)
- # cryogen (12)
- # cursive (16)
- # data-science (4)
- # datomic (39)
- # events (2)
- # fulcro (5)
- # gorilla (3)
- # introduce-yourself (3)
- # jobs (9)
- # kaocha (5)
- # malli (16)
- # music (12)
- # off-topic (11)
- # polylith (4)
- # react (4)
- # reactive (1)
- # reagent (18)
- # remote-jobs (2)
- # reveal (2)
- # sci (4)
- # shadow-cljs (31)
- # timbre (4)
- # tools-build (70)
- # tools-deps (11)
- # vim (33)
- # xtdb (53)
How can I call .toArray
with a typed array argument without the compiler using reflection? I'm stumped =\
@U1Z5X06NP nope
(defn to-long-array
[^java.util.Collection coll ^longs arr]
(.toArray coll ^"[J" arr))
is reflectivepublic static Object invokeStatic(final Object coll, final Object arr) {
return Reflector.invokeInstanceMethod(coll, "toArray", new Object[] { arr });
}
or try a concrete class not an interface.
The regular Object array gives me this:
((ArrayList)(new ArrayList())).toArray((Object[])((IFn)const__3.getRawRoot()).invoke(PersistentVector.EMPTY));
So, no reflection. :)The original line is
(.toArray ^java.util.ArrayList (java.util.ArrayList.) (to-array []))
that's why it's convoluted.why not (long-array [1 2 3])
?
So that's why one of the reasons why neither longs
nor "[J"
will work, if I understand that statement and the right arity of toArray
correctly.
(ns x
(:import (java.util ArrayList)))
(def ^"[Ljava.lang.Object;" la (make-array Long 0))
(def a (ArrayList.))
(.toArray ^ArrayList a la)
Results in
((ArrayList)const__14.getRawRoot()).toArray((Object[])const__3.getRawRoot());
But wouldn't it still be useless in Clojure, given that in run time it's still Object[]
?
is there a reason not to use long-array
?
Here's the run time type of the 1-arity of .toArray
:
{:name toArray,
:return-type java.lang.Object<>,
:declaring-class java.util.ArrayList,
:parameter-types [java.lang.Object<>],
:exception-types [],
:flags #{:public}}
@U7RJTCH6J it returns a primitive type
I'm pretty sure you can simply call to-array
if you need boxed values. The result in Clojure will still be the same.
No need for interop at all. Although .toArray
might be a tad more efficient, if you care about it in this particular case.
if you want [Ljava.lang.Long;
, then use
> (type (into-array Long [1 2 3]))
[Ljava.lang.Long;
Ah, so the runtime type is different. Huh. Got confused by my outdated knowledge on type erasure.
this macro will also type hint it for you https://github.com/valerauko/iny/blob/87ce05f95e4830f932374366fab615ef4b8d8993/src/iny/interop.clj#L3-L8