类似于 ? 的三元运算符: [英] Ternary Operator Similar To ?:

查看:53
本文介绍了类似于 ? 的三元运算符:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图避免这样的结构:

I am trying to avoid constructs like this:

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

好的,在这个例子中,thenelse 分支很简单,但你可以想象复杂的分支.我构建了以下内容:

Ok, in this example the then and else branch are simple, but you can image complex ones. I built the following:

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

定义为,我可以将上面的简单示例替换为:

Defined that, I can replace the above simple example with:

this.getClass.getSimpleName is {s: String => s.endsWith("$")} ? {s: String => s.init} :: {s: String => s}

但是我怎样才能摆脱 s: String => ?我想要这样的东西:

But how can I get rid of the s: String =>? I want something like that:

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

我猜编译器需要额外的东西来推断类型.

I guess the compiler needs the extra stuff to infer types.

推荐答案

我们可以结合 如何在 Scala 中定义一个保留前导标记的三元运算符?Option 包装值是一种好的模式吗?得到

We can combine How to define a ternary operator in Scala which preserves leading tokens? with the answer to Is Option wrapping a value a good pattern? to get

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

这是否足以满足您的需求?

Is this adequate for your needs?

这篇关于类似于 ? 的三元运算符:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆