一个有关Scala的简单问题


object extendBuiltins extends Application {
def fact(n: Int): BigInt =
if (n == 0) 1 else fact(n-1) * n
class Factorizer(n: Int) {
def ! = fact(n)
}
implicit def int2fact(n: Int) = new Factorizer(n)

println("10! = " + (10!))
}



这是官方网站原来的代码,我改了一下,变成下面的样子:


object extendBuiltins extends Application {
def fact(n: Int): BigInt =
if (n == 0) 1 else fact(n-1) * n
class Factorizer(n: Int) {
def ! = fact(n)
}
class Factorizer2(n: Int) {
def a = fact(n)
}
implicit def a(n: Int) = new Factorizer(n)
implicit def b(n: Int) = new Factorizer2(n)

println("10! = " + (10!))
println("10! = " + (10.a))
}



我的问题是:为什么“!”,就可以直接挂在10后面,而“a”,就一定要加一个“.”在前面呢?
问题补充
再看一个:


object implicits extends Application {
implicit def arrayWrapperA =
new {
def !(p: (A, A) => Boolean) = {
util.Sorting.stableSort(x, p); x
}
}
val x = Array(2, 3, 1, 4)
println("x = "+ x.!((x: Int, y: Int) => x < y))
}


这里面的“!”,前面不加“.”,也会报错。。。

似乎 10a 和 x! 会被解析成一个 identifier,而 10! 则可以被区分开 …… 中间都加个空格应该就没事了 ……

[url]http://www.scala-lang.org/docu/files/ScalaReference.pdf[/url]
[url]http://stackoverflow.com/questions/1006967/scala-which-characters-can-i-omit[/url]