0

我正在尝试编译此 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"
                  ^

关于如何在 Scala 上解决类型擦除问题给出的答案?或者,为什么我不能获取我的集合的类型参数?似乎指向了同样的问题。但我无法在这种特定情况下推断出解决方案。

4

2 回答 2

4

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

Scala 不能match使用类型参数。

于 2013-02-14T06:56:11.257 回答
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
}
于 2013-02-14T07:29:45.000 回答