为什么我在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")
  }

我希望打印"found",但打印的是"not found"。我试着匹配任何有Int, Boolean, Int

三个元素的List

您正在检查包含伴随对象Int和Boolean的列表。它们与Int和Boolean类不同。

使用类型化模式。

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

Scala参考资料,第8.1节描述了你可以使用的不同模式

第一个问题是get方法返回一个Option:

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

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

接下来,您将检查列表是否再次包含对象 Int, BooleanInt,而不是如果它包含类型Int, BooleanInt的对象。

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")

下面的代码也适用于Scala 2.8

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

最新更新