Archive

Archive for August 7th, 2010

Scala: 方法名约定

August 7th, 2010 leeing 2 comments

Scala中没有操作符但是支持运算符重载,方法的最后一个字符也对优先级有影响,它决定了方法调用的目标。

Scala的这个约定在熟悉之后你会发现它提高了流畅性,例如,如果想要将一个值添加到一list中,可以写作:value::list,尽管可以读为:“value被附加到list上”,这个方法的目标实际上list而参数是value,也就是说list.::(value)。

如果方法名以冒号结尾,那调用目标是操作符后面的实例,在下一个例子中,^() 是一个定义在类Cow中的方法,而 ^:() 是一个定义在Moon中的方法:

class Cow {
	def ^(moon: Moon) = println("Cow jumped over the moon")
}
class Moon {
	def ^:(cow: Cow) = println("This cow jumped over the moon too")
}

调用如下:

val cow = new Cow
val moon = new Moon
cow ^ moon
cow ^: moon

Read more…

Categories: Scala Tags: