如何绕过这个scala编译器擦除警告?

时间:2013-02-14 06:10:38

标签: scala

我正在尝试编译此scala代码并获取以下编译器警告。

scala> val props: Map[String, _] = 
 |   x match {
 |     case t: Tuple2[String, _] => {
 |       val prop =
 |       t._2 match {
 |         case f: Function[_, _] => "hello"
 |         case s:Some[Function[_, _]] => "world"
 |         case _ => t._2
 |       }
 |     Map(t._1 -> prop)
 |   }
 |   case _ => null
 | }
<console>:10: warning: non-variable type argument String in type pattern (String, _) is unchecked since it is eliminated by erasure
       case t: Tuple2[String, _] => {
               ^
<console>:14: warning: non-variable type argument _ => _ in type pattern Some[_ => _] is unchecked since it is eliminated by erasure
           case s:Some[Function[_, _]] => "world"
                  ^

How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?给出的答案似乎指向了同样的问题。但我不能在这个特定的背景下推断出一个解决方案。

2 个答案:

答案 0 :(得分:4)

使用case t @ (_: String, _)代替case t: Tuple2[String, _]case s @ Some(_: Function[_, _])代替case s:Some[Function[_, _]]

Scala在类型参数上不能match

答案 1 :(得分:2)

我会像这样重写它:

x match {
  case (name, method) => {
    val prop =
      method match {
        case f: Function[_, _] => "hello"
        case Some(f: Function[_, _]) => "world"
        case other => other
      }

    Map(name -> prop)
  }
  case _ => null
}