TL ; DR:
A constructor is a special method that runs automatically when you create an object. It's used to set up the object's initial state.
In Scala, the class header is the constructor: list the fields as
varparameters and Scala creates and sets them when the object is created:class Dog(var name: String, var age: Int)
Then create objects with arguments:
Dog("Rex", 4)— the constructor fills in the fields for you.
Full lesson:
In the previous lesson you set fields after creating the object:
val dog = Dog()
dog.name = "Rex"
dog.age = 4
That works, but it's noisy and easy to forget. Constructors let you initialize the fields the moment Dog(...) is called.
Defining a constructor
A Scala class has a primary constructor, and its parameter list sits right in the class header:
Parameters marked
var(orval) also become fields of the object, so there is nothing else to declare.A class with no body needs no braces at all.
class Dog(var name: String, var age: Int)
Parameters become fields
Because the header says var name: String, the parameter and the field are the same thing: Scala stores the argument in the field name for you, so you never write this.name = name yourself.
Calling the constructor
val rex = Dog("Rex", 4)
val luna = Dog("Luna", 7)
By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna.
The default constructor
If a class has no parameter list, Scala gives it a no-argument constructor — that's why Dog() worked in earlier lessons. The moment you add parameters to the header, that freebie disappears: from now on you must call Dog with the arguments you specified.
Your task
Declare the Dog class with a constructor that takes name: String and age: Int as var parameters. Then in mainFunction, create two dogs:
val rex = Dog("Rex", 4)
val luna = Dog("Luna", 7)
Expected output:
Rex is 4
Luna is 7Free plan: 30 tutor messages. PRO is unlimited.
