4.1. Creating a Primary Constructor
Problem
You want to create a primary constructor for a class, and you quickly find that the approach is different than Java.
Solution
The primary constructor of a Scala class is a combination of:
The constructor parameters
Methods that are called in the body of the class
Statements and expressions that are executed in the body of the class
Fields declared in the body of a Scala class are handled in a manner similar to Java; they are assigned when the class is first instantiated.
The following class demonstrates constructor parameters, class fields, and statements in the body of a class:
classPerson(varfirstName:String,varlastName:String){println("the constructor begins")// some class fieldsprivatevalHOME=System.getProperty("user.home")varage=0// some methodsoverridedeftoString=s"$firstName $lastName is $age years old"defprintHome{println(s"HOME = $HOME")}defprintFullName{println(this)}// uses toStringprintHomeprintFullNameprintln("still in the constructor")}
Because the methods in the body of the class are part of the
constructor, when an instance of a Person class is created, you’ll see the output
from the println statements at the
beginning and end of the class declaration, along with the call to the
printHome and printFullName methods near the bottom of the
class:
scala> val p = new Person("Adam", "Meyer")
the constructor begins
HOME = /Users/Al
Adam Meyer is 0 years old
still in the constructorDiscussion
If you’re ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access