`Any` 上的模式匹配作为 2 元组?
Pattern Matching on `Any` as 2-tuple?
给出以下函数:
scala> def foo(x: Any) = x match {
| case _: (String, Int) => "foo"
| case _ => "bar"
| }
我收到以下编译时警告:
<console>:8: warning: non-variable type argument String in type pattern (String, Int) is unchecked since it is eliminated by erasure
case _: (String, Int) => "foo"
^
foo: (x: Any)String
我对 JVM 擦除(即针对 List[T]
)的理解是,在运行时,JVM 不知道 T
的类型。
请解释为什么上面的 is unchecked since it is eliminated by erasure
显示为尝试在 2 元组上进行模式匹配。
元素类型只是 Tuple2 的类型参数。
但是你可以:
scala> (("hi",42): Any) match { case (_: String, _: Int) => }
给出以下函数:
scala> def foo(x: Any) = x match {
| case _: (String, Int) => "foo"
| case _ => "bar"
| }
我收到以下编译时警告:
<console>:8: warning: non-variable type argument String in type pattern (String, Int) is unchecked since it is eliminated by erasure
case _: (String, Int) => "foo"
^
foo: (x: Any)String
我对 JVM 擦除(即针对 List[T]
)的理解是,在运行时,JVM 不知道 T
的类型。
请解释为什么上面的 is unchecked since it is eliminated by erasure
显示为尝试在 2 元组上进行模式匹配。
元素类型只是 Tuple2 的类型参数。
但是你可以:
scala> (("hi",42): Any) match { case (_: String, _: Int) => }