我试图避免像这样的构造:
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}
我猜编译器需要额外的东西来推断类型。
发布于 2011-02-10 00:45:16
我们可以将How to define a ternary operator in Scala which preserves leading tokens?与Is Option wrapping a value a good pattern?的答案结合起来,以获得
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
这是否足以满足您的需求?
发布于 2011-02-10 00:52:34
用basic Scala表示的Rex Kerr’s answer:
"Hi".getClass.getSimpleName match {
case x if x.endsWith("$") => x.init
case x => x
}
尽管我不确定你想要优化if-else结构的哪一部分。
发布于 2018-02-13 21:53:42
由于Scala中的if-else结构返回值,因此可以使用
val a = if (1 < 0) 1 else 2
更多信息:https://alvinalexander.com/scala/scala-if-then-ternary-operator-cookbook-examples
https://stackoverflow.com/questions/4947535
复制相似问题