How to fix an exhaustive template warning?

Some scala code:

val list = List(Some("aaa"), Some("bbb"), None, ...)

list.filter(_!=None).map {
  case Some(x) => x + "!!!"
  // I don't want to handle `None` case since they are not possible
  // case None
}

When I run it, the compiler complains:

<console>:9: warning: match may not be exhaustive.
It would fail on the following input: None
                  list.filter(_!=None).map {
                                   ^
res0: List[String] = List(aaa!!!, bbb!!!)

How to fix this warning without providing a string case None?

+4
source share
5 answers

If you use mapafter filter, you can use collect.

list collect { case Some(x) => x + "!!!" } 
+11
source

you can use flatten

scala> val list = List(Some("aaa"), Some("bbb"), None).flatten
list: List[String] = List(aaa, bbb)

scala> list.map {
     |   x => x + "!!!" 
     | }
res1: List[String] = List(aaa!!!, bbb!!!)
+3
source

@unchecked, :

list.filter(_!=None).map { x => ( x : @unchecked) match {
  case Some(x) => x + "!!!"
 }
}
+1

get .
  :

scala> val list = List(Some("aaa"), Some("bbb"), None)
list: List[Option[String]] = List(Some(aaa), Some(bbb), None)
scala> list.filter(_ != None).map(_.get + "!!!")
res0: List[String] = List(aaa!!!, bbb!!!)
0

- , filter pattern matching

scala> list.flatten map (_ + "!!!") 

scala> list.flatMap (_ map (_ + "!!!"))
0

Source: https://habr.com/ru/post/1548448/


All Articles