Search code examples
rubyinteropjrubyrubymine

Why does the to_java method convert (what would be) an integer in Java, to Long?


Why does the to_java method convert the integral value of 1 to the Java::JavaLang::Long class, instead of the Integer calss?

Here is an example of this method in action:

puts 1.to_java.class

In normal Java, the value 1, if placed in a wrapper class, would be a memeber of Java.lang.Integer (correct me if I am wrong). Why, in Ruby, is 1.to_java a member of Java::JavaLang::Long?


Solution

  • simply because Fixnum in JRuby is represented internally as a (primitive) long field (check RubyFixnum.java) thus by default Fixnum#to_java simply returns it's internal Java value

    same goes for Bigint - internally represented as BigInteger so you get one using to_java

    ... you can provide a conversion hint: 1.to_java(:int).class # Java::JavaLang::Integer