thesamet
thesamet

Reputation: 6582

Idiomatic way to possibly compose a function

I am building a value through a series of chaining function calls (all results are of type B):

val o: Option[String] = ...
val b: B = someFunc()
    .map(func1)
    .map(func2)
    .map(/* want to apply func3 here if o.isDefined)

Now, I have func3: (B, String) => B which I want to apply only if o is defined, and in that case I also want to pass it the value of the option as the second parameter. This would be equivalent to:

val tmp: B = someFunc()
    .map(func1)
    .map(func2)
val b = o.fold{b}{v => func3(tmp, v)}

But I wouldn't like to break the call chain. Any idiomatic way to do this?

Upvotes: 0

Views: 109

Answers (1)

Nikita Volkov
Nikita Volkov

Reputation: 43310

The obvious simple but not elegant solution is the following:

val b = someFunc().map(func1).map(func2)
  .map( a => if( o.isDefined ) func3( a, v ) else a )

Here's an a bit modified version of the one you suggested:

val b = someFunc().map(func1).map(func2)
  .map( a => o.foldLeft( a )( func3 ) )

Upvotes: 1

Related Questions