user3124181
user3124181

Reputation: 863

Conditionally Apply Methods in Scala Elegantly

Is there a clean way to conditionally apply methods in a long list of methods? I want to do something like this. (whether or not method2 is called, the type of object remains the same so that method3 is still valid)

someObject
    .method1()
    if (some condition) {.method2()}
    .method3()

This would achieve the same thing as below but I would like to avoid rewriting it completely for each condition, ie

if (some condition){
    someObject
        .method1()
        .method2()
        .method3()
}
else {
    someObject
        .method1()
        .method3()
}

Upvotes: 1

Views: 240

Answers (1)

Mario Galic
Mario Galic

Reputation: 48430

Try pipe chaining operator, for example

import scala.util.chaining._

object SomeObject {
  def method1 = { println("method1"); this }
  def method2 = { println("method2"); this }
  def method3 = { println("method3"); this }
}

SomeObject
  .method1
  .pipe(someObject => if (condition) someObject.method2 else someObject)
  .method3

which if condition == false outputs

method1
method3

otherwise outputs

method1
method2
method3

Upvotes: 5

Related Questions