Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix the pattern-matching exhaustive 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 that warning without providing the case None line?

like image 347
Freewind Avatar asked Jul 15 '14 06:07

Freewind


2 Answers

If you are using map after filter, you may to use collect.

list collect { case Some(x) => x + "!!!" } 
like image 79
Eastsun Avatar answered Oct 03 '22 14:10

Eastsun


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!!!)
like image 39
Govind Singh Avatar answered Oct 03 '22 14:10

Govind Singh