Welcome! Please see the About page for a little more info on how this works.

0 votes
ago in Clojure by

This code resorts to reflection:

(long (char \x))

call to static method longCast on clojure.lang.RT can't be resolved (argument types: char).

Casting to int does not trigger this reflection warning, as RT.intCast(char) exists.

It seems to me there should be a RT.longCast(char) as well?

1 Answer

0 votes
ago by
edited ago by

char is not a numeric type but has a mapping into int specifically. So there are no numeric casts to any other numeric type.

You don't really need the char here either - \x is a char:

user=> (long \a)
97

or you could do:

user=> (long (int (char \a)))
97
ago by
Thanks for your reply!

I tried to come up with a minimal reproducing example. My original function looked like this, bit-xor-ing all characters in a string:

  (defn- simple-checksum [s]
    (reduce #(bit-xor %1(long (Character/toLowerCase (char %2)))) 0 s))

I can of course replace `long` with `int` here, or make the char using `(int)` because `toLowerCase` exists as `int -> int` as well.

However, it looked wrong to me to cast to `int` and then implicitly to `long` (`Numbers.xor()`). Of course this is a micro-optimisation and can maybe elided by the compiler completely.

Still, I was surprised to see the reflection warning because you can implicitly convert a `char` to a `long` in Java --- is Clojure stricter than its host here?
...