Created
November 23, 2011 07:30
-
-
Save ggd543/1388106 to your computer and use it in GitHub Desktop.
一个比较难懂的隐式转换过程
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object TernaryOp { | |
class Ternary[T](t: T) { | |
println("Ternary") | |
def is[R](bte: BranchThenElse[T,R]) = { | |
println("is ... ") | |
if (bte.branch(t)) bte.then(t) else bte.elze(t) | |
} | |
} | |
class Branch[T](branch: T => Boolean) { | |
println("branch"); | |
def ?[R] (then: T => R) = { println("?"); new BranchThen(branch,then) } | |
} | |
class BranchThen[T,R](val branch: T => Boolean, val then: T => R){ | |
println("BranchThen") | |
} | |
class Elze[T,R](elze: T => R) { | |
println("Elze") | |
def :: (bt: BranchThen[T,R]) = { println("::"); 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) | |
def test = { | |
this.getClass.getSimpleName is {s: String => s.endsWith("$")} ? {s: String => s.init} :: {s: String => s} | |
// 等价于 test2 | |
} | |
def test2 = { | |
this.getClass.getSimpleName is (({s: String => s.endsWith("$")} ? {s: String => s.init}) :: {s: String => s}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
对于TernaryOp.test来说,结果显示的先后顺序是
Ternary
branch
?
BranchThen
Elze
::
is ...
res36: String = TernaryOp
其中XX是一个数字,与REPL当时的状态有关。
其实只要明确
is
,?
和::
的执行顺序(关于函数(或方法,运算符的)的优先级请查阅《Programming in Scala 》第5.8节),那么就不难解读TernaryOp.test的实现。这三个函数的执行顺序依次是:?
,::
,is