我试图避免像这样的构造:
val result = this.getClass.getSimpleName
if (result.endsWith("$")) result.init else result
好的,在本例中,then
和else
分支很简单,但是您可以想象复杂的分支。我构建了以下代码:
object TernaryOp {
class Ternary[T](t: T) {
def is[R](bte: BranchThenElse[T,R]) = if (bte.branch(t)) bte.then(t) else bte.elze(t)
}
class Branch[T](branch: T => Boolean) {
def ?[R] (then: T => R) = new BranchThen(branch,then)
}
class BranchThen[T,R](val branch: T => Boolean, val then: T => R)
class Elze[T,R](elze: T => R) {
def :: (bt: BranchThen[T,R]) = new BranchThenElse(bt.branch,bt.then,elze)
}
class BranchThenElse[T,R](val branch: T => Boolean, val then: T => R, val elze: T => R)
implicit def any2Ternary[T](t: T) = new Ternary(t)
implicit def fct2Branch[T](branch: T => Boolean) = new Branch(branch)
implicit def fct2Elze[T,R](elze: T => R) = new Elze(elze)
}
定义后,我可以将上面的简单示例替换为:
this.getClass.getSimpleName is {s: String => s.endsWith("$")} ? {s: String => s.init} :: {s: String => s}
但是怎样才能摆脱s: String =>
呢?我想要这样的东西:
this.getClass.getSimpleName is {_.endsWith("$")} ? {_.init} :: {identity}
我猜编译器需要额外的东西来推断类型。
https://stackoverflow.com/questions/4947535
复制相似问题