Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does integer type casting works in java interop?

public class Hello {
  public static void test(int i) {
    System.out.println("int");
  }

  public static void test(long l) {
    System.out.println("long");
  }
}


user=> (def foo 1)
#'user/foo

user=> (type foo)
java.lang.Long

user=> (Hello/test 1)
long
nil

user=> (Hello/test foo)
int
nil

user=> (Integer. 1)
1

user=> (Integer. foo)
1

user=> (Short. 1)
IllegalArgumentException No matching ctor found for class java.lang.Short  clojure.lang.Reflector.invokeConstructor (Reflector.java:183)

I couldn't figure out the rules.

like image 384
alice Avatar asked Nov 29 '25 04:11

alice


1 Answers

In short, Clojure does not have the same overloading behavior as Java. It is a different language (that runs on the JVM) with its own set of rules. So if you define a method test(short s) it will work because you have a specific matching method signature, but the Clojure compiler won't otherwise do a widening conversion to the "closest" method.

For a more complete discussion with links, see my answer to this question: Clojure overloaded method resolution for Longs

like image 97
noahlz Avatar answered Dec 01 '25 00:12

noahlz