为什么我的模式匹配集合在Scala中失败?

时间:2011-09-21 08:48:00

标签: scala pattern-matching

我的代码如下

  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

类型的三个元素的List

3 个答案:

答案 0 :(得分:18)

您正在检查包含随播对象IntBoolean的列表。这些与班级IntBoolean不同。

改为使用类型化模式。

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

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

答案 1 :(得分: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")

答案 2 :(得分:3)

以下内容也适用于Scala 2.8

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