Search code examples
scalahigher-order-functionsidiomsscala-option

Process Scala Option type with higher-order functions


There is a class

class MyType {
  def status(): String = "Connected" // demo implementation
}

I have a val x: Option[Option[MyType]]. I need to process this value like the following:

x match {
  case None => "Error1"
  case Some(None) => "Error2"
  case Some(Some(t)) => t.status
}

I would like to rewrite the same code with higher order functions as it described in Tom Morris post. What is the correct way to code it?


There are some words about the motivation to ask the question. Official documentation says:

The most idiomatic way to use an scala.Option instance is to treat it as a collection or monad and use map,flatMap, filter, or foreach <...> A less-idiomatic way to use scala.Option values is via pattern matching

I am not quite sure I realize what "idiomatic" means exactly, but it sounds like "good" for me.


Solution

  • Something like this?

    x.fold("Error1")(_.fold("Error2")(_.status()))