Reputation: 198398
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?
Upvotes: 6
Views: 1367
Reputation: 15490
some other way to solve this issue, without filter
and pattern matching
scala> list.flatten map (_ + "!!!")
or
scala> list.flatMap (_ map (_ + "!!!"))
Upvotes: 0
Reputation:
You can use get
method instead of pattern matching.
Here is example code:
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!!!)
Upvotes: 0
Reputation: 15490
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!!!)
Upvotes: 3
Reputation: 2747
You could use the @unchecked
annotation, although that requires some additional code:
list.filter(_!=None).map { x => ( x : @unchecked) match {
case Some(x) => x + "!!!"
}
}
Upvotes: 2
Reputation: 18869
If you are using map
after filter
, you may to use collect
.
list collect { case Some(x) => x + "!!!" }
Upvotes: 12