WestCoastProjects
WestCoastProjects

Reputation: 63201

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.

Upvotes: 1

Views: 1489

Answers (2)

Mikel San Vicente
Mikel San Vicente

Reputation: 3863

Your question is not very clear, is this what you are looking for?

foo.map(_.bar)

Upvotes: 2

ale64bit
ale64bit

Reputation: 6242

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.

Upvotes: 5

Related Questions