Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
&引用;“通过擦除消除”;Scala警告_Scala_Tuples - Fatal编程技术网

&引用;“通过擦除消除”;Scala警告

&引用;“通过擦除消除”;Scala警告,scala,tuples,Scala,Tuples,我有一个检查四元组输入的代码,如下所示: if (v.isInstanceOf[(Int, Int, Int, Int)]) { val value = v.asInstanceOf[(Int, Int, Int, Int)] 我从Scala编译器中获得了通过擦除消除的警告: 8: non-variable type argument Int in type (Int, Int, Int, Int) is unchecked since it is eliminated by erasu

我有一个检查四元组输入的代码,如下所示:

if (v.isInstanceOf[(Int, Int, Int, Int)]) {
  val value = v.asInstanceOf[(Int, Int, Int, Int)]
我从Scala编译器中获得了通过擦除消除的警告

8: non-variable type argument Int in type (Int, Int, Int, Int) is unchecked since it is 
eliminated by erasure
[warn]     if (v.isInstanceOf[(Int, Int, Int, Int)]) {

这是为了什么,以及如何更改代码以删除警告?

在JVM上,类型参数或“泛型”在类文件字节码中被“擦除”。仅保留基类型。例如,如果你有

val v: Tuple4[Int, Int, Int, Int] = (1, 2, 3, 4)
那么在运行时只能将此类型标识为

Tuple4[_, _, _, _]
在大多数情况下,这并不重要,因为类型检查发生在编译时,所以信息仍然存在。但是,如果在运行时有一个值,并且在运行时测试它是否是
Tuple4
的实例,则该tuple的元素类型是未知的

换句话说,对于任何
Tuple4
,无论值是否为整数,您的
if
子句都将是
true
。使用
(“a”,“b”,3.4,true)尝试您的测试
,它将“匹配”:


好的方面是,如果您在运行时有一个值,那么您可以只测试单个元组元素:

def test2(v: Any): Option[(Int, Int, Int, Int)] = v match {
  case (a: Int, b: Int, c: Int, d: Int) => Some((a, b, c, d))
  case _ => None
}

test2((1, 2, 3, 4)).map(_._1)  // Some 1
test2(("a", 'b', 3.4, true)).map(_._1)  // None

出于好奇,为什么要在运行时检查类型?!
def test2(v: Any): Option[(Int, Int, Int, Int)] = v match {
  case (a: Int, b: Int, c: Int, d: Int) => Some((a, b, c, d))
  case _ => None
}

test2((1, 2, 3, 4)).map(_._1)  // Some 1
test2(("a", 'b', 3.4, true)).map(_._1)  // None