如何抑制“匹配不彻底!"Scala 中的警告 [英] How to suppress "match is not exhaustive!" warning in Scala
问题描述
如何抑制匹配不详尽!"以下 Scala 代码中的警告?
How can I suppress the "match is not exhaustive!" warning in the following Scala code?
val l = "1" :: "2" :: Nil
l.sliding(2).foreach{case List(a,b) => }
到目前为止我发现的唯一解决方案是用额外的匹配语句包围模式匹配:
The only solution that I found so far is to surround the pattern matching with an additional match statement:
l.sliding(2).foreach{x => (x: @unchecked) match {case List(a,b) => }}
然而,这使得代码不必要地复杂且难以阅读.所以必须有一个更短、更易读的替代方案.有人知道吗?
However this makes the code unnecessarily complex and pretty unreadable. So there must be a shorter and more readable alternative. Does someone know one?
我忘了提到我的列表 l
在我的程序中至少有 2 个元素.这就是为什么我可以安全地抑制警告.
I forgot to mention that my list l
has at least 2 elements in my program. That's why I can safely suppress the warning.
推荐答案
这里有几个选项:
您可以匹配
Seq
而不是List
,因为Seq
没有详尽检查(这将失败,就像你原来的一样,在一个元素列表中):
You can match against
Seq
instead ofList
, sinceSeq
doesn't have the exhaustiveness checking (this will fail, like your original, on one element lists):
l.sliding(2).foreach{case Seq(a, b) => ... }
你可以使用 a for comprehension,它会默默地丢弃任何不匹配的东西(所以它不会对一个元素列表做任何事情):
You can use a for comprehension, which will silently discard anything that doesn't match (so it will do nothing on one element lists):
for (List(a, b) <- l.sliding(2)) { ... }
你可以使用 collect
,它也会默默地丢弃任何不匹配的东西(以及你将在哪里获得一个迭代器,如果你需要):
You can use collect
, which will also silently discard anything that doesn't match (and where you'll get an iterator back, which you'll have to iterate through if you need to):
l.sliding(2).collect{case List(a,b) => }.toList
这篇关于如何抑制“匹配不彻底!"Scala 中的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!