2011-09-21 59 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") 
相关问题