I am learning Scala and struggling with Option[Seq[String]]
object I need to process. There is a small array of strings Seq("hello", "Scala", "!")
which I need to filter against charAt(0).isUpper
condition.
Doing it on plain val arr = Seq("hello", "Scala", "!")
is as easy as arr.filter(_.charAt(0).isUpper)
. However, doing the same on Option(Seq("hello", "Scala", "!"))
won't work since you need to call .getOrElse
on it first. But even then how can you apply the condition?
arr.filter(_.getOrElse(false).charAt(0).isUpper
is wrong. I have tried a lot of variants and searching stackoverflow didn't help either and I am wondering if this is at all possible. Is there an idiomatic way to handle Option
wrapped cases in Scala?
You can just call foreach or map on the option, i.e. arr.map(seq => seq.filter(_.charAt(0).isUpper))