javadba javadba - 2 months ago 5
Scala Question

How to invoke a method on an Option in scala only if the entry exists (is not None)


class Foo {
def bar() = println("bar")
val fooOpt = Option[Foo]

The following should be (is??) a simple construct in Scala but it has so far eluded me.

fooOpt.getOrElse(None).<logic to invoke if exists>(

Note : I need the logic to be inline and not something like

if (fooOpt.isDefined) { }

The point is to achieve a builder pattern/structure.


You can do:


Alternatively, if you want to transform the value inside the Option into something else, use map instead:

Not sure if that's what you want, though.