Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 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 Answer

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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...