I am having issues with the following code in Scala
import org.junit.Test
import org.junit.Assert._
class BoxingTest {
val holder: Holder[Integer] = new Holder[Integer]();
@Test
def Holder_Eq_Primitive(){
assertEquals(holder, holder eq 1);
}
@Test
def Holder_Eq_Boxed(){
assertEquals(holder, holder eq 1.asInstanceOf[Integer]);
}
}
class Holder[T] {
def eq(other: T): Holder[_] = this;
}
I get the following error in compilation
/BoxingTest.scala:12: error: type mismatch;
[INFO] found : Int
[INFO] required: AnyRef
[INFO] Note: primitive types are not implicitly converted to AnyRef.
[INFO] You can safely force boxing by casting x.asInstanceOf[AnyRef].
[INFO] assertEquals(holder, holder eq 1);
[INFO] ^
[ERROR] one error found
[INFO] -------------------------
Why doesn’t the implicit conversion from Int to Integer handle the issue?
I could easily fix the code by not using eq, but this just doesn’t seem right. IMHO the available implicit conversions should be applied here.
UPDATE
I got the issue fixed by using the signature like this
import org.junit.Test
import org.junit.Assert._
class BoxingTest {
@Test
def Holder_Eq_Primitive(){
val holder: Holder[Int] = new Holder[Int]();
assertEquals(holder, holder eq 1);
}
@Test
def Holder_Eq_Boxed(){
val holder: Holder[Integer] = new Holder[Integer]();
assertEquals(holder, holder eq 1.asInstanceOf[Integer]);
}
}
class Holder[T] {
def eq(other: T): Holder[_] = ...;
}
Still, it would be good to use the wrapper types instead.
I tried comparing an
Intvalue against integer literal and got some interesting note from the compiler. This may shed some light about the causes of this behaviour.