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

del*_*ber 3 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")
  }
Run Code Online (Sandbox Code Playgroud)

我希望打印出"找到"但打印出"未找到".我正在尝试匹配任何具有Int,Boolean,Int三种元素的List

ret*_*nym 18

您正在检查包含伴随对象IntBoolean的列表.这些与IntBoolean类不同.

请改用Typed Pattern.

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

Scala参考,第8.1节描述了您可以使用的不同模式.