2013-02-14 40 views
0

我想编译这个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?上给出的答案似乎指向同样的问题。但我无法在这个特定的背景下推断出解决方案。

+0

如何'x'定义? – Brian 2013-02-14 06:14:27

+0

x可以是任何物体或功能的任何东西 – sobychacko 2013-02-14 18:05:19

回答

4

使用case t @ (_: String, _)而不是case t: Tuple2[String, _]case s @ Some(_: Function[_, _])而不是case s:Some[Function[_, _]]

关于类型参数,斯卡拉不能match

+0

非常感谢!它照顾了警告。 – sobychacko 2013-02-14 17:57:52

+0

case t:WrappedArray [Tuple2 [String,_]] => { - 也会产生相同类型的擦除警告。你能指出我为什么如此吗? – sobychacko 2013-02-15 04:03:33

+0

@sobychacko这是因为类型擦除:在运行时'jvm'中'WrappedArray [(String,Int)]'和'WrappedArray [String]'是相同的:'WrappedArray [Object]'。关于类型参数的信息仅在编译时才可用。有关某些链接和解决方法,请参见[this](http://www.scalafied.com/60/lightweight-type-erasure-matching)。 – senia 2013-02-15 05:09:14

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 
} 
+0

感谢您的回复。我喜欢这两种方法。 – sobychacko 2013-02-14 17:58:25