Given the following code:
import collection.JavaConversions._ def j(x: java.util.List[java.lang.Integer]): Unit = // the function body here can be any valid code println (x) val a = List(1) I get a type mismatch error when I call this:
j (seqAsJavaList(a)) Here is the error from REPL
<console>:13: error: type mismatch; found : List[Int] required: Seq[Integer] f (seqAsJavaList(a)) ^ However, I can call this with no error:
j(seqAsJavaList(List(1))) I'm using 2.11.2.
Can someone explain to me why seqAsJavaList behaves differently? Thanks.
Adding more context/clarification to my original question:
What I meant to ask was "why does seqAsJavaList behave differently when operating on a predefined variable a than on an in-place value List(1) when they are of the same type?" Furthermore seqAsJavaList(a) and seqAsJavaList (List(1)) return exactly the same signature java.util.List[Int]. Using the substitution model, one would expect both j (seqAsJavaList(a)) and j (seqAsJavaList (List(1)) ) to succeed. And yet, only the latter works. When both seqAsJavaList(a) and seqAsJavaList (List(1)) are java.util.List[Int], why does one usage handle Int well and the other doesn't?
Another note:
I just tried collection.JavaConverters and the result is not ideal but at least consistent:
// The definitions of j & a are the same as above. I repeat them here to save some page scrolling. // BTW, instead of f, I use j to indicate it is supposed to be a Java static method. // I mock it in Scala so that this can be easily run in REPL. def j ( ls: java.util.List [java.lang.Integer] ): Unit = println (ls) val a = List( 1 ) // new code here import collection.JavaConverters._ // Both require the explicit casting to work j ( a.map (i => i: java.lang.Integer).asJava ) j ( List(1).map (i => i: java.lang.Integer).asJava ) // These fail with the same error. j( a.asJava ) j( List(1).asJava ) // <console>:12: error: type mismatch; // found : java.util.List[Int] // required: java.util.List[Integer] // j ( List(1).asJava ) // ^