ฉันพยายามหลีกเลี่ยงโครงสร้างเช่นนี้:
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}
ฉันเดาว่าคอมไพเลอร์ต้องการสิ่งพิเศษในการอนุมานประเภท
HasIs
,IsWithCondition
,ConditionAndTrueCase
ชั้นเรียนที่จะสร้างขึ้นเป็นส่วนหนึ่งของการแสดงออกจากซ้ายไปขวา).