How to suppress “match is not exhaustive!” warning in Scala

前端 未结 4 2037
我在风中等你
我在风中等你 2020-12-11 00:09

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) =&         


        
4条回答
  •  悲&欢浪女
    2020-12-11 01:10

    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
      

提交回复
热议问题