I am having problems 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 compilation error
/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 is the implicit conversion from Int to Integer not implied?
I could easily fix the code without using eq, but that just doesn't seem right. IMHO, the available implicit conversions should be applied here.
UPDATE
I have a problem fixed using such a signature
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[_] = ...;
}
However, it would be useful to use wrapper types.
source
share