Scala eq questions

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.

+3
source share
2 answers

I tried to compare the value Intwith a whole literal and got an interesting note from the compiler. This may shed light on the reasons for this behavior.

scala> val a = 1
scala> a eq 1
<console>:6: error: type mismatch;
 found   : Int
 required: ?{val eq: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method int2Integer in object Predef of type (Int)java.lang.Integer
 and method intWrapper in object Predef of type (Int)scala.runtime.RichInt
 are possible conversion functions from Int to ?{val eq: ?}
       a eq 1
       ^
+2
source

, Type Erasure Java.

class Holder[T] {

    def eq(other: T): Holder[_] = this;
}

T . :

enter image description here

, Int AnyVal, AnyRef. , eq 1, Int, .

PS: Int java.lang.Integer, , RichInt.

+1

Source: https://habr.com/ru/post/1795180/


All Articles