0

I have an Option of a string. I want to update the contained value:

if(x.isEmpty) {
  ...another calculation
} else {
  x.map(val => ...update val)
}

Is this an idiomatic way?

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
Mandroid
  • 6,200
  • 12
  • 64
  • 134

3 Answers3

4
x.fold(another calculation)(v => ...update v)

e.g.

x.fold("no value")("Value is " + _)

Note that this extracts the value from the Option so if you want to have the result as an Option you need to wrap it in Some.

Tim
  • 26,753
  • 2
  • 16
  • 29
2

Note that if your inner computation gets too long or unreadable for a fold, there's always good old-fashioned pattern matching.

x match {
  case None => {
    // None case ...
  }
  case Some(y) => {
    // Some case (y is the inside) ...
  }
}

Like everything in Scala, this is an expression, so it can be assigned to a variable or used in another other expression you like.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
1

Alternatively, using the lazy keyword:

// T is the type of the value
val valueOpt: Option[T] = ???
lazy val backupValue: T = ??? // Other calculation, but only evaluated if needed

val value: T = valueOpt.map( v => /*Update v*/ ).getOrElse( backupValue )
// do something with the value you want to manipulate