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?
If you want to apply f: X => Y to a value x of type X, you write f(x).
If you want to apply f: X => Y to a value ox of type Option[X], you write ox.map(f).
You seem to already know what you want to do with the sequence, so just put the appropriate f into map.
Example:
val ox = Option(Seq("hello", "Scala", "!"))
ox.map(_.filter(_(0).isUpper)) // Some(Seq("Scala"))
You can just call foreach or map on the option, i.e. arr.map(seq => seq.filter(_.charAt(0).isUpper))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With