有没有一种干净的方法可以有条件地在一长串方法中应用方法?我想做这样的事情。(无论是否调用method2,对象类型保持不变,method3仍然有效)
someObject
.method1()
if (some condition) {.method2()}
.method3()
Run Code Online (Sandbox Code Playgroud)
这将实现与下面相同的事情,但我想避免为每个条件完全重写它,即
if (some condition){
someObject
.method1()
.method2()
.method3()
}
else {
someObject
.method1()
.method3()
}
Run Code Online (Sandbox Code Playgroud)
尝试pipe链接运算符,例如
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
Run Code Online (Sandbox Code Playgroud)
如果condition == false输出
method1
method3
Run Code Online (Sandbox Code Playgroud)
否则输出
method1
method2
method3
Run Code Online (Sandbox Code Playgroud)