[英]scala.MatchError in scala map
I am trying scala here https://scastie.scala-lang.org/cUSu8uROQRy4llFWMaQ3bw . 我在这里尝试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"
}
The error is: 错误是:
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
Why? 为什么? how to fix it? 如何解决? thanks 谢谢
Some of the entries of the list don't match the pattern because of the n1 != 2
condition. 由于n1 != 2
条件,列表中的某些条目与模式不匹配。 Obviously, (2,(1,aa))
does not satisfy this condition. 显然, (2,(1,aa))
不满足此条件。 So you get a match error. 因此,您会遇到匹配错误。 You have at least two obvious ways to fix it. 您至少有两种明显的方法来修复它。
First possibility: use for-yield
, which will desugar into map
and withFilter
: 第一种可能性:使用for-yield
,它将被withFilter
为map
和withFilter
:
for ((n1, (n2, st)) <- days; if(n1!=2) ) yield s"st = $st"
Second possibility: use collect
: 第二种可能性:使用collect
:
val r2 = days collect {
case (n1, (n2, st)) if(n1!=2) => s"st = $st"
}
Both results in: 两者都导致:
List(st = a, st = b, st = c)
List(st = a, st = b, st = c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.