我对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;
}我在编译过程中出现以下错误
/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] -------------------------为什么从Int到Integer的隐式转换不能处理这个问题?
我可以很容易地通过不使用eq来修正代码,但这似乎不太正确。IMHO可用的隐式转换应该在这里应用。
更新
我用这样的签名解决了问题
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[_] = ...;
}不过,最好还是使用包装器类型。
发布于 2011-03-20 17:19:53
我尝试将Int值与整数文本进行比较,并从编译器那里得到了一些有趣的注释。这可能说明了这种行为的原因。
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
^发布于 2011-11-27 13:00:54
我认为这是关于Java 的。当您编译类时
class Holder[T] {
def eq(other: T): Holder[_] = this;
}类型T将被删除。你可以做一个测试:

另一方面,Int类是AnyVal的子类型,而不是AnyRef。因此,如果尝试使用带有参数1 (类型为Int)的方法Int,则会发出运行时错误。
PS:虽然Int可以隐式地转换为java.lang.Integer,但正如Vilius所指出的,它也可以隐式地转换为RichInt。
https://stackoverflow.com/questions/5139962
复制相似问题