javadba javadba - 4 months ago 17
Scala Question

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

Consider:

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>(_.bar)


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

if (fooOpt.isDefined) { fooOpt.get.bar }


The point is to achieve a builder pattern/structure.

Answer

You can do:

foo.foreach(_.bar)

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

foo.map(_bar)

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

Comments