我在我的代码中多次发现这种模式:
if (doIt)
object.callAMethod
else
object
我想知道是否有一种语法上更令人愉悦的方式来编写上面的代码,尤其是避免object
变量的重复。就像是:
// using the Scalaz "pipe" operator
// and "pimping" f: T => T with a `when` method
object |> (_.callAMethod).when(doIt)
不幸的是,上面的行失败了,因为类型推断需要一个参数类型(_.callAMethod)
。
我现在最好的方法是:
implicit def doItOptionally[T](t: =>T) = new DoItOptionally(t)
class DoItOptionally[T](t: =>T) {
def ?>(f: T => T)(implicit doIt: Boolean = true) =
if (doIt) f(t) else t
}
implicit val doIt = true
object ?> (_.callAMethod)
不是很好,因为我必须声明一个,implicit val
但如果有几个链式调用,这会得到回报:
object ?> (_.callAMethod) ?> (_.callAnotherMethod)
有没有人有更好的主意?我在这里错过了一些 Scalaz 魔法吗?