scala地图中的scala.MatchError

时间:2018-05-16 16:50:28

标签: scala scala-collections

我在这里尝试scala https://scastie.scala-lang.org/cUSu8uROQRy4llFWMaQ3bw

val days = List((1, (2, "a")), (1, (3, "b")), (1, (1, "c")), (2, (1, "aa")), (2, (2, "bb")))

val r = days map {
  case (n1, (n2, st)) if(n1!=2) => s"st = $st"
}

错误是:

scala.MatchError: (2,(1,aa)) (of class scala.Tuple2)

java.lang.ExceptionInInitializerError
    at Main.main(main.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sbt.Run.invokeMain(Run.scala:67)
    at sbt.Run.run0(Run.scala:61)
    at sbt.Run.sbt$Run$$execute$1(Run.scala:51)
    at sbt.Run$$anonfun$run$1.apply$mcV$sp(Run.scala:55)
    at sbt.Run$$anonfun$run$1.apply(Run.scala:55)
    at sbt.Run$$anonfun$run$1.apply(Run.scala:55)
    at sbt.Logger$$anon$4.apply(Logger.scala:84)
    at sbt.TrapExit$App.run(TrapExit.scala:248)
    at java.lang.Thread.run(Thread.java:748)
Caused by: scala.MatchError: (2,(1,aa)) (of class scala.Tuple2)
    at Playground.$anonfun$r$1(main.scala:5)
    at scala.collection.immutable.List.map(List.scala:287)
    at Playground.<init>(main.scala:5)
    at Main$.<init>(main.scala:10)
    at Main$.<clinit>(main.scala)
    ... 14 more

为什么呢?怎么解决?感谢

1 个答案:

答案 0 :(得分:2)

由于n1 != 2条件,列表中的某些条目与模式不匹配。显然,(2,(1,aa))不满足这个条件。所以你得到一个匹配错误。你有至少两种明显的方法来解决它。

第一种可能性:使用for-yield,将mapwithFilter

for ((n1, (n2, st)) <- days; if(n1!=2) ) yield s"st = $st"

第二种可能性:使用collect

val r2 = days collect {
  case (n1, (n2, st)) if(n1!=2) => s"st = $st"
}

两者都导致:

List(st = a, st = b, st = c)
List(st = a, st = b, st = c)