我在我的代码中多次发现这种模式:
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 魔法吗?
最佳答案
class When[A](a: A) {
def when(f: A => Boolean)(g: A => A) = if (f(a)) g(a) else a
}
implicit def whenever[A](a: A) = new When(a)
例子:
scala> "fish".when(_.length<5)(_.toUpperCase)
res2: java.lang.String = FISH
关于scala - Scala 中方法的条件调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7313604/