Black monkey house: Scala construction order and defined in advance

When a subclass overrides a method or field in the parent class, parent class and rely on these fields or methods initialization, this time there will be problems, such as

class Creature {
 val range: Int = 10
 val env: Array[Int] = new Array[Int](range)
//lazy val env: Array[Int] = new Array[Int](range)
}

class Ant extends Creature {
 //override val range = 2
 override val range = 2
}
-------------------------------------------------------------
val ant = new Ant
println(ant.range)
println(ant.env.length)

At this time, the order of configuration

(1) Ant constructor before invoking its own constructor, call the constructor Creature

(2) Creature configuration it will range field is set to 10

(3) Creature env constructor for initializing the array, call range () value is

(. 4) which range is rewritten to output the field value range (not yet initialized) class of the Ant

(5) range method returns 0, (which is an initial value for all fields of shaping space when the object is assigned)

(6) env array of length is set to zero.

(7) Ant constructor continues, its range field is set to 2.

So the size of the env is the number? Is 0, no surprise surprise, meaning not an accident?

Problem solving, four kinds of programs

(1) sub-class does not override the superclass

(2) val may be declared final, so subclasses can not be rewritten.

(3) val declared in the superclass lazy, but not so safe and efficient.

(4) defines the syntax may also be used in advance to be before the superclass constructor performs initialization subclass field val

Defined in advance, subversion three ways to view, ha ha ~ ~
looked like multiple inheritance, but it is not multiple inheritance

class Ant2 extends {
 override val range = 3
} with Creature

Reproduced in: https: //www.jianshu.com/p/d66ae2359968

Guess you like

Origin blog.csdn.net/weixin_34281537/article/details/91182497