## 三元运算符类似于？：内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (58)

``````val result = this.getClass.getSimpleName
if (result.endsWith("\$")) result.init else result
``````

``````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}
``````

``````this.getClass.getSimpleName is {_.endsWith("\$")} ? {_.init} :: {identity}
``````

### 2 个回答

``````scala>   "Hi".getClass.getSimpleName |> {x => x.endsWith("\$") ? x.init | x}
res0: String = String

scala> List.getClass.getSimpleName |> {x => x.endsWith("\$") ? x.init | x}
res1: String = List
``````

``````case class Bool(b: Boolean) {
def ?[X](t: => X) = new {
def |(f: => X) = if(b) t else f
}
}

object Bool {
implicit def BooleanBool(b: Boolean) = Bool(b)
}
``````

``````object T {   val condition = true

import Bool._

// yay!
val x = condition ? "yes" | "no"
}
``````