为什么用成员变量声明为元组的这种擦除警告? [英] Why this erasure warning with member variables declared as a tuple?
问题描述
看看这个Scala类:
class示例{
val(x,y):( Int,Int)=(1,2)
}
编译此结果会产生警告:
Example.scala:2:警告:类型模式
中的非变量类型参数Int Int,Int )未被选中,因为通过擦除
val(x,y)消除了:(Int,Int)=(1,2)
^
删除显式类型注释可避免此警告:
类示例{
val(x,y)=(1,2)
}
为什么我会收到警告,为什么删除显式类型注释会删除它呢?据我所知,没有什么真正的变化, x
和 y
仍为 Int类型
不带类型批注。
您可以将示例重写为:
类示例{
val Tuple2(x,y):Tuple2 [Int,Int] = Tuple2(1,2)
}
此模式匹配实际上由2个匹配组成-现在它说:取右边的对象键入 Tuple2 [Int,Int]
并在 unapply [Int,Int]
> Tuple2 随播对象。然后, unapply [Int,Int]
会验证该对象确实具有 Tuple2
类型,其结果值将为用于将值绑定到变量 x
和 y
。
此后,此模式匹配包含:Tuple2 [Int,Int]
,因此它尝试执行 isInstanceOf [Tuple2 [Int,Int] ]
动态检查对象是否另外具有类型 Tuple2 [Int,Int]
。但是,泛型类型信息在运行时会被删除,因此编译器警告说,它实际上无法生成验证类型参数 [Int,Int]
实例化该对象的代码。 / p>
以相同的方式,按照以下模式匹配:
val a:AnyRef =(1、2)
a比赛{
情况t2:Tuple [Int,Int] =>
}
您也会收到类似的警告。
Have a look at this Scala class:
class Example {
val (x, y): (Int, Int) = (1, 2)
}
Compiling this results in a warning:
Example.scala:2: warning: non variable type-argument Int in type pattern
(Int, Int) is unchecked since it is eliminated by erasure
val (x, y): (Int, Int) = (1, 2)
^
Removing the explicit type annotation gets rid of this warning:
class Example {
val (x, y) = (1, 2)
}
Why do I get the warning and why does removing the explicit type annotation get rid of it? As far as I can see nothing really changes, x
and y
are still of type Int
without the type annotation.
You could rewrite your example to:
class Example {
val Tuple2(x, y): Tuple2[Int, Int] = Tuple2(1, 2)
}
This pattern match actually consists of 2 matches - it now says: take the right hand side object of type Tuple2[Int, Int]
and call the method unapply[Int, Int]
on the Tuple2
companion object. The unapply[Int, Int]
will then verify that the object really has the type Tuple2
, and its result value will be used to bind values to variables x
and y
.
After that, this pattern match contains : Tuple2[Int, Int]
, so it tries to do an isInstanceOf[Tuple2[Int, Int]]
check dynamically to see if the object additionally has the type Tuple2[Int, Int]
. However, generic type information is erased at runtime, so the compiler warns that it cannot actually produce code which verifies that the object is instantiated for type parameters [Int, Int]
.
In the same way, in the following pattern match:
val a: AnyRef = (1, 2)
a match {
case t2: Tuple[Int, Int] =>
}
you would get a similar warning.
这篇关于为什么用成员变量声明为元组的这种擦除警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!