Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract sequence elements wrapped in Option in Scala?

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?

like image 215
minerals Avatar asked Oct 19 '25 03:10

minerals


2 Answers

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"))
like image 164
Andrey Tyukin Avatar answered Oct 21 '25 19:10

Andrey Tyukin


You can just call foreach or map on the option, i.e. arr.map(seq => seq.filter(_.charAt(0).isUpper))

like image 26
Sebastiaan van den Broek Avatar answered Oct 21 '25 20:10

Sebastiaan van den Broek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!