Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ggd543/1392907 to your computer and use it in GitHub Desktop.
Save ggd543/1392907 to your computer and use it in GitHub Desktop.
关于方法执行顺序的问题
class Op(var x : Int) {
def +++(op: Op) = { println(this.x+ " +++ "+op.x); this.x += op.x; this;}
def ***(op: Op) = { println(this.x+ " *** " + op.x); this.x *= op.x ; this;}
}
val op1 = new Op(1)
val op2 = new Op(2)
val op3 = new Op(3)
val op4 = new Op(4)
op1 +++ op2 +++ op3 *** op4 //be equivalent to op1 +++ op2 +++ (op3 *** op4)
class AA{
var i= 0
def /: (s: String) = {
println("s = " +s);
s+"!"
}
def /: (aa : AA) = {
println(aa.i);
aa.i = aa.i+ 1
this;
}
def is(s: String)= { println(s); i = i +1 ; this }
def isThis(s: String) = { println("isThis: "+s); i= i + 1; s}
def add(i: Int) = { println("add "+i+" to "+this.i); this.i += i; this }
}
val aa = new AA
aa is "tree" is "AA" /: aa // 等价于 aa.is("tree").is(aa./:("AA"))
aa is "tree" isThis "AA" /: aa // 等价于 aa.is("tree").isThis(aa./:("AA"))
aa is "tree" add 2 /: aa // 报错. (aa is "tree" add 2) /: aa 才等价于 aa./:(aa.is("tree").add(2))
class AA{
var i= 0
def /: (s: String) = {
println("s = " +s);
s+"!"
}
def /: (aa : AA) = {
println(aa.i);
aa.i = aa.i+ 1
this;
}
def is(s: String)= { println(s); i = i +1 ; this }
def isThis(s: String) = { println("isThis: "+s); i= i + 1; s}
def add(i: Int) = { println("add "+i+" to "+this.i); this.i += i; this }
}
val aa = new AA
aa is "tree" is "AA" /: aa // 等价于 aa.is("tree").is(aa./:("AA"))
aa is "tree" isThis "AA" /: aa // 等价于 aa.is("tree").isThis(aa./:("AA"))
aa is "tree" add 2 /: aa // 报错. (aa is "tree" add 2) /: aa 才等价于 aa./:(aa.is("tree").add(2))
@ggd543
Copy link
Author

ggd543 commented Nov 25, 2011

注意执行的结果.
scala中,函数(或方法,运算符)的优先级是由函数名(或方法名,运算符)的第一个字符决定的。详细请查阅《Programming in Scala,2nd》第5.8节

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment