返回首页 Scala 抽象成员

预先初始化成员的值

为了解决上篇中 RationalTrait 的问题,有两个解决方案,第一方案是使用预先初始化成员的值的方法,这种方法可以让你在调用父类构造函数之前首先初始化子类的成员。 这种方法,是把初始化成员变量的定义放在调用父构造函数之前。

下面是一个匿名实例化 Trait 的例子


val x = 1

new {
    val numerArg =1 * x
    val denomArg = 2 *x
} with RationalTrait

res1: RationalTrait = 1/2

可以看到在这个例子中,我们把初始化成员的代码放在其父 Trait 之前。 再看一个例子:


object twoThirds extends {
    val numerArg =1 * x
    val denomArg = 2 *x
} with RationalTrait

defined object twoThirds

初始化成员部分也是防止其父 Trait 之前,两个方法都使用 with。

这种方法除了可以应用中匿名实例和对象外,也可以应用中类的定义说,比如我们可以定义如下的 RationalClass


class RationalClass(n:Int,d:Int) extends {
    val numerArg =n
    val denomArg =d
} with RationalTrait {
    def + (that: RationalClass) = new RationalClass(
        numer * that.denom + that.numer * denom,
        denom * that.denom
    )
}

因为这些预先初始化的值发生在调用父类的构造函数之前,因此这些初始化这些值时不可以引用正在构造的对象,正因为如此,如果在初始化的表达式中使用 this,这个 this 不是指正在构造的对象,而是指包含这个定义的对象。比如:


new {
    val numberArg =1
    val denomArg = this.numerArg *2
} with RationalTrait

<console>:11: error: value numerArg is not a member of object $iw
              val denomArg = this.numerArg *2

这个例子无法编译,这是因为编译器无法找到 对象 $iw 的 numerArg 成员,$iw 为 Scala 命令行输入的当前对象。