Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Tuple type inference in Java

Tags:

java

scala

This is probably a very noobish question, but I was playing a bit with Scala/Java interaction, and was wondering how well did Tuples play along.

Now, I know that the (Type1, Type2) syntax is merely syntactic sugar for Tuple2<Type1, Type2>, and so, when calling a Scala method that returns a Tuple2 in a plain Java class, I was expecting to get a return type of Tuple2<Type1, Type2>

For clarity, my Scala code:

def testTuple:(Int,Int) = (0,1)

Java code:

Tuple2<Object,Object> objectObjectTuple2 = Test.testTuple();

It seems the compiler expects this to be of parameterized types <Object,Object>, instead of, in my case, <Integer,Integer> (this is what I was expecting, at least).

Is my thinking deeply flawed and is there a perfectly reasonable explanation for this?

OR

Is there a problem in my Scala code, and there's a way of being more... explicit, in the cases that I know will provide an API for Java code?

OR

Is this simply a limitation?

like image 647
pcalcao Avatar asked Apr 20 '12 14:04

pcalcao


1 Answers

Int is Scala's integer type, which is a value class, so it gets special treatment. It is different from java.lang.Integer. You can specify java.lang.Integer specifically if that's what you need.

[dlee@dlee-mac scala]$ cat SomeClass.scala 
class SomeClass {
  def testIntTuple: (Int, Int) = (0, 1)
  def testIntegerTuple: (java.lang.Integer, java.lang.Integer) = (0, 1)
}

[dlee@dlee-mac scala]$ javap SomeClass
Compiled from "SomeClass.scala"
public class SomeClass implements scala.ScalaObject {
  public scala.Tuple2<java.lang.Object, java.lang.Object> testIntTuple();
  public scala.Tuple2<java.lang.Integer, java.lang.Integer> testIntegerTuple();
  public SomeClass();
}
like image 169
leedm777 Avatar answered Sep 23 '22 17:09

leedm777