user1826663
user1826663

Reputation: 377

Scala: what is the real difference between fields in a class and parameters in the constructor

What is the difference between these two classes:

class Person {
  var name : String = _
  var surname: String = _
}

class Person (var name:String, var surname: String)

name and surname are always fields in Class Person. Equally? I just change the way you instantiate the class Person. Is that right?

Upvotes: 20

Views: 5615

Answers (2)

idonnie
idonnie

Reputation: 1713

I've compiled both versions of a class:

class PersonV0 {
  var name : String = _
  var surname: String = _
}

class PersonV1 (var name:String, var surname: String)

The difference is constructors:

public experimental.PersonV0();
  Code:
   0:   aload_0
   1:   invokespecial   #23; //Method java/lang/Object."<init>":()V
   4:   return
}

public experimental.PersonV1(java.lang.String, java.lang.String);
  Code:
   0:   aload_0
   1:   aload_1
   2:   putfield    #12; //Field name:Ljava/lang/String;
   5:   aload_0
   6:   aload_2
   7:   putfield    #16; //Field surname:Ljava/lang/String;
   10:  aload_0
   11:  invokespecial   #24; //Method java/lang/Object."<init>":()V
   14:  return
}

Upvotes: 7

drexin
drexin

Reputation: 24403

The difference between the two is, that in the second case, the fields are also parameters for the constructor. If you declare the parameters to be either val or var, they automatically become public members. If you have no var/val there and don't use the variables anywhere but in the constructor, they will not become members, if you do, they will be private members. If you would make them case classes, you would in the first case have no unapply for the variables.

So to answer your question: In this case you are right, you just change the way you set the values.

edit:

Tip: you can see, what the scala compiler generates, if you call the compiler with -print, this also works for the REPL.

Upvotes: 17

Related Questions