Scala object initialization sequence in the built-in hierarchy

I am new to scala from java and am confused by the sequence of initializing the scala object in my own hierarchy. IIRC, in Java, if a subclass object is initialized, the constructor of its base class is called before any code of its own constructor. In scala, I get a completely different behavior. Consider the following example:

class Point(val x: Int, val y: Int){ val name = this.makeName; def makeName: String = { println("makeName at super."); "[" + x + ", " + y + "]"; } override def toString: String = name; } class ColorPoint(override val x: Int, override val y: Int, var color: String) extends Point(x, y) { // key statement println(name); override def makeName: String = { println("makeName at sub."); super.makeName + ":" + myColor; } val myColor = color; override def toString: String = name; } 

Let's just take a look at the byte code of the ColorPoint constructor dumped with javap . If the code contains a println(name); key operator println(name); then byte code

 public ColorPoint(int, int, java.lang.String); Code: 0: aload_0 1: aload_3 2: putfield #13; //Field color:Ljava/lang/String; 5: aload_0 6: iload_1 7: iload_2 8: invokespecial #18; //Method Point."<init>":(II)V 11: getstatic #24; //Field scala/Predef$.MODULE$:Lscala/Predef$; 14: aload_0 15: invokevirtual #28; //Method name:()Ljava/lang/String; 18: invokevirtual #32; //Method scala/Predef$.println:(Ljava/lang/Object;)V 21: aload_0 22: aload_3 23: putfield #34; //Field myColor:Ljava/lang/String; 26: return 

We see that the myColor field myColor initialized after invokespecial , that is, after the initialization of the base class.

If I comment on the println(name); statement println(name); , then the byte code:

 public ColorPoint(int, int, java.lang.String); Code: 0: aload_0 1: aload_3 2: putfield #13; //Field color:Ljava/lang/String; 5: aload_0 6: aload_3 7: putfield #15; //Field myColor:Ljava/lang/String; 10: aload_0 11: iload_1 12: iload_2 13: invokespecial #20; //Method Point."<init>":(II)V 16: return 

We see that the myColor field myColor initialized immediately before invokespecial , i.e. before initializing the database.

Then what is the reason? Does any document / article define this type of behavior?

BTW, my scala version is 2.7.7final (OpenJDK Server VM, Java 1.6.0_20). Thanks and best regards!

+4
source share
1 answer

The compiler just does everything in order. There is documentation here.

https://github.com/paulp/scala-faq/wiki/Initialization-Order

The main part of them is as follows.

  • Superclasses are fully initialized before subclasses.
  • Otherwise, in the order of the announcement.
+3
source

Source: https://habr.com/ru/post/1384268/


All Articles