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?
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.
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.
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.
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.
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 class
es, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With