4

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?

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
minerals
  • 6,090
  • 17
  • 62
  • 107

3 Answers3

4

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"))
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
3

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

Sebastiaan van den Broek
  • 5,818
  • 7
  • 40
  • 73
3

You can use a pattern matching for that case as

Option(Seq("hello", "Scala", "!")) match {
      case Some(x) => x.filter(_.charAt(0).isUpper)
      case None => Seq()
    }
Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
  • @AndreyTyukin thats something to return when Option returns None :) – Ramesh Maharjan Jul 05 '18 at 16:30
  • 1
    I think that debugging code that returns `Seq("None")` might be just as fun as debugging large administrative legacy web-apps that fail to process people with [surname "Null"](http://www.bbc.com/future/story/20160325-the-names-that-break-computer-systems) properly... – Andrey Tyukin Jul 05 '18 at 16:32
  • No, just change it to more natural choice `Seq()`, then it's fine imho ;) – Andrey Tyukin Jul 05 '18 at 16:35