scala: updating string value in an option

258 views Asked by At

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?

3

There are 3 answers

0
Tim On BEST ANSWER
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.

0
Randomness Slayer On

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
0
Silvio Mayolo On

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.