Home > database >  scala: updating string value in an option
scala: updating string value in an option

Time:07-08

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?

CodePudding user response:

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.

  • Related