Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
user1826663 Avatar asked Nov 25 '12 08:11

user1826663


People also ask

What is field in Scala?

What are fields in Scala? Fields are basically keeping the state of an object. Unlike in Java, Scala fields are of two types i.e Mutable fields and immutable fields. So we can declare mutable fields by using the keyword var and immutable fields by using the keyword val.

What is constructor parameter in Scala?

If the parameters in the constructor parameter-list are declared using var, then the value of the fields may change. And Scala also generates getter and setter methods for that field. If the parameters in the constructor parameter-list are declared using val, then the value of the fields cannot change.

What is the use of constructor in Scala?

Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.

What is the difference between class and object in Scala?

Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.


1 Answers

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.

like image 171
drexin Avatar answered Oct 08 '22 04:10

drexin