私はこのような構造を避けるためにしようとしています:三項演算子?:
val result = this.getClass.getSimpleName
if (result.endsWith("$")) result.init else result
[OK]を、この例では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}
私は推測するには、コンパイラは種類を推測する余分なものが必要だと思います。
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
を取得するために
を - あなたの「理由問題は左から右にタイプ推論が最適ですが、オペレータの優先順位のためにトークンを右から左にバインドしていることです。あなたの言葉をすべて同じ言葉で(同じ優先順位で)作って、一緒にグループ化する方法を変えれば、あなたが望む推論を得ることができます。 (つまり、左から右へ式の一部を構築する 'HasIs'、' IsWithCondition'、 'ConditionAndTrueCase'クラスがあります) –
私は無意識のうちに型推論の方法を左から右に推測しましたが、演算子の優先順位他の英数字の前に '?'で始まり、メソッド名の最初のcharとして、そして左の連想のために ':'で始まるメソッド名の連想性。だから、タイプ推論を左から右へ動かすために、新しいメソッド名を考え直さなければならない。ありがとう! –