关键字this指向当前执行方法被调用的对象实例。或者如果使用在构造器里的话,就是正被构建的对象实例。例如,如果要添加方法lessThan,测试当前有理数是否小于传入的参数,可以这样写:
class Rational(:Int,d:Int) { require(d != 0) val number:Int = n val denom:Int = d override def toString = number + "/" + denom def add(that:Rational):Rational = { new Rational(number * that.denom + that.number * d,d * that.denom) } def lessThan(that:Rational) = { this.number * that.demon < that.number * this.denom //注意这里 }}
这里,this.number指向lessThan被调用的那个对象的分子。你也可以去掉this前缀而只写number,两种写法意义相同。下面是不能省略this的例子,在Rational类里添加max方法返回指定有理数和参数中的较大者:
class Rational(n:Int,d:Int) { require(d != 0) //先决条件 val number:Int = n val denom:Int = d override def toString = number + "/" + denom def add(that:Rational):Rational = { new Rational(number * that.denom + that.number * d,d * that.denom) } def lessThan(that:Rational) = { this.number * that.denom < that.number * this.denom } def max(that:Rational) = { if(this.lessThan(that)) that else this //注意这里 }}
这里,第一个this可写可不写,写成(lessThan(that))也是一样的,但第二个this必须写,表示要返回的对象。