Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

pattern matching - How to suppress "match is not exhaustive!" warning in 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?

Edit

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here are several options:

  1. You can match against Seq instead of List, since Seq doesn't have the exhaustiveness checking (this will fail, like your original, on one element lists):

    l.sliding(2).foreach{case Seq(a, b) => ... }
    
  2. 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)) { ... }
    
  3. 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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...