Scala继承中val变量的构造顺序
例子1:
class A { val x1: String = "hello" val x2: String = "mom" println("A: x1=" + x1 + ",x2=" + x2) } class B extends A { override val x2: String = "dad" println("B: x1=" + x1 + ",x2=" + x2) } object ValTest extends App { new A println() new B }
输出:
A: x1=hello,x2=mom A: x1=hello,x2=null B: x1=hello,x2=dad
例子2:
class A { val x1: String = "hello" val x2: String = x2 println("A: x1=" + x1 + ",x2=" + x2) } class B extends A { override val x1: String = "dad" println("B: x1=" + x1 + ",x2=" + x2) } object ValTest extends App { new A println() new B }
输出:
A: x1=hello,x2=null A: x1=null,x2=null B: x1=dad,x2=null