Scala Class body or primary constructor body

Refresh

April 2019

Views

303 time

1

It's a very basic question. Out of curiosity, I wanted to know whether in the below code:

class A(str: String) {
//body here...
}

is it Scala Class body or primary constructor body or instance initializer body (like Java)?

1 answers

3

Is it Scala Class body or primary constructor body or instance initializer body?

It is the class body. Anything defined between the opening and closing parenthesis which requires initialization will be initialized when the constructor is invoked.

For example, if we add a println statement inside the body, we'll see it execute immediately when invoking the constructor:

class A(str: String) {
  println("inside body")
}

new A("hello")

In regards to the JVM class emitted, we can see that the body of the code was lifted to the constructor of the class:

public class A$1 {
  public A$1(java.lang.String);
    Code:
       0: aload_0
       1: invokespecial #17                 // Method java/lang/Object."<init>":()V
       4: getstatic     #23                 // Field scala/Predef$.MODULE$:Lscala/Predef$;
       7: ldc           #25                 // String inside body
       9: invokevirtual #29                 // Method scala/Predef$.println:(Ljava/lang/Object;)V
      12: return
}