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

前端 未结 4 2033
我在风中等你
我在风中等你 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 00:55

    Since your sliding(2) can possibly return one last list with only one element in it, you should also test it:

    l sliding(2) foreach {
      case a::b::Nil => println("two elements: " + a + b)
      case l         => println("one last element" + l.head)
    }
    

提交回复
热议问题