2011-09-21 58 views
3

我的代碼如下爲什麼我的模式匹配集合在Scala中失敗?

val hash = new HashMap[String, List[Any]] 
    hash.put("test", List(1, true, 3)) 
    val result = hash.get("test") 
    result match { 
    case List(Int, Boolean, Int) => println("found") 
    case _ => println("not found") 
    } 

我希望「發現」來進行打印,但「未找到」被打印出來。我試圖在任何具有Int,Boolean,Int三種元素的列表上匹配

回答

18

您正在檢查包含伴隨對象IntBoolean的列表。這些不同於類IntBoolean

改用Typed Pattern。

val result: Option[List[Any]] = ... 
result match { 
    case Some(List(_: Int, _: Boolean, _: Int)) => println("found") 
    case _          => println("not found") 
} 

Scala Reference第8.1節描述了您可以使用的不同模式。

3

下也適用於斯卡拉2.8

List(1, true, 3) match { 
    case List(a:Int, b:Boolean, c:Int) => println("found") 
    case _ => println("not found") 
} 
4

的第一個問題是,get方法返回一個Option

scala> val result = hash.get("test") 
result: Option[List[Any]] = Some(List(1, true, 3)) 

所以你需要來匹配Some(List(...)),不List(...)

其次,要檢查如果列表中包含對象IntBooleanInt再次,如果不包含對象,它們的類型IntBooleanInt一次。

IntBoolean都是類型和對象同伴。試想一下:

scala> val x: Int = 5 
x: Int = 5 

scala> val x = Int 
x: Int.type = object scala.Int 

scala> val x: Int = Int 
<console>:13: error: type mismatch; 
found : Int.type (with underlying type object Int) 
required: Int 
     val x: Int = Int 
        ^

因此正確匹配語句應該是:

case Some(List(_: Int, _: Boolean, _: Int)) => println("found") 
相關問題