2013-02-14 64 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