The constructor in Scala is more special than that in Java. It can be divided into two types: Master constructor, slave constructor. The main constructor is mixed with the definitions of fields and methods in the class.
In Scala, you do not need to define a method with the same class name in the class as Java to act as a constructor.
The parameter list of the main constructor is written after the class name, And the constructor content is written directly in the class definition. Therefore, in a Scala class, except for the definition of methods and fields, all the code is the content of the main constructor.
class Fruit(n: String, w: Int) { val name = n val weight = w println("This is a " + n)
println("Weight = " + w)}
If a fruit object is defined next.
val apple = new Fruit("Apple", 10)
It will print on the screen:
This is a apple
Weight = 10
Because
println("This is a " + n)println("Weight = " + w)
The two lines of code are also the content of the constructor.
In addition to the master constructor, scala also has a slave constructor that uses parameters different from the master constructor to initialize objects.
The definition of the constructor starts with Def this.
For example, if the default weight of fruit is 10.
class Fruit(n: String, w: Int) { val name = n val weight = w println("This is a " + n) println("Weight = " + w) def this(n: String) = this(n, 10)}
val orange = Fruit("Orange")
The slave constructor on Scala also has certain limitations, which is written in Scala programming.
"The first action of each slave constructor in Scala is to call other constructor in the same class. In other words
That is, each slave constructor in each Scala class starts with "This. Called Structure
It can be either the main Constructor (like the rational example) or the calling constructor earlier than in the text.
Other slave constructor. The fundamental result of this rule is that each Scala constructor call will end
The call of the main constructor. Therefore, the main constructor is the only entry point of the class ."
Constructor in Scala