Scala’s default structure function
In Scala, if no main constructor function is specified, the compiler will generate a constructor for the main constructor function. The object declaration of all classes is handled as part of the constructor. This is also called the default constructor.
Scala default base structure example
class Student{
println("Hello from default constructor");
}
Scala’s core constructor function
Scala provides the basic structural function type concept. If your code has only one constructor, you cannot specify an explicit constructor. This helps optimize the code and can generate a main structure with zero or more parameters.
An example of a Scala core structure function
class Student(id:Int, name:String){
def showDetails(){
println(id+" "+name);
}
}
object Demo{
def main(args:Array[String]){
var s = new Student(1010,"Maxsu");
s.showDetails()
}
}
Save the above code in the source file:ScaleIn between, compile and run your code with the following command
D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo
1010 Maxsu
Scala secondary constructor (helper)
You can create any number of helper constructors in a class, and the main constructor must be called inside the helper constructor.this
The keywords are used to call the constructor from within other constructors. When calling other constructors, put them on the first line of the constructor.
Scala example of a secondary structure function
class Student(id:Int, name:String){
var age:Int = 0
def showDetails(){
println(id+" "+name+" "+age)
}
def this(id:Int, name:String,age:Int){
this(id,name) // Calling primary constructor, and it is first line
this.age = age
}
}
object Demo{
def main(args:Array[String]){
var s = new Student(1010,"Maxsu", 25);
s.showDetails()
}
}
Save the above code in the source file:ScaleIn between, compile and run your code with the following command
D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo
1010 Maxsu 25
Scala example: heavy load constructors
In Scala, the constructor can be loaded. Let’s look at the example below.
class Student(id:Int){
def this(id:Int, name:String)={
this(id)
println(id+" "+name)
}
println(id)
}
object Demo{
def main(args:Array[String]){
new Student(101)
new Student(100,"Minsu")
}
}
Save the above code in the source file:ScaleIn between, compile and run your code with the following command
D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo
101
100
100 Minsu