DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. How to Use the Auxiliary Constructor in Scala

How to Use the Auxiliary Constructor in Scala

Take a look at this post to learn more about using the auxiliary constructor, as well as how to use it with other constructors, in Scala.

Randhir Singh user avatar by
Randhir Singh
·
Aug. 13, 18 · Tutorial
Like (5)
Save
Tweet
Share
34.08K Views

Join the DZone community and get the full member experience.

Join For Free


Scala-Constructor-Auxillary

Before starting with the auxiliary constructor, I recommend that you take a look at my previous blog — Primary Constructor in Scala.

Scala has two types of constructors:

1. primary constructor

2. auxiliary constructor (secondary constructor)

A scala class can contain zero or more auxiliary constructors. The auxiliary constructor in Scala is used for constructor overloading and defined as a method usingthis  name.
The auxiliary constructor must call either previously defined auxiliary constructors or primary constructors in the first line of its body. Hence, every auxiliary constructor invokes directly or indirectly to a primary constructor.

We can call the primary constructor or other auxiliary constructor using this .

Here is an example:

scala> class Employee(empId: Int,name: String,salary :Double){
| def this()
| {
| this(0,"",0.0)
| println("Zero-argument auxiliary constructor")
| }
| println("Primary construtor")
| }
defined class Employee

scala> val emp = new Employee()
Primary construtor
Zero-argument auxiliary constructor
emp: Employee = Employee@7186b202


As shown above, when we create an object using the zero-argument auxiliary constructor, then there is the first statement this(0,””,0.0) which will call to a primary constructor. The first primary constructor body will be executed after the auxiliary constructor body.

We can also call directly to the primary constructor:

scala> val emp = new Employee(101,"Smith",50000)
Primary construtor
emp: Employee = Employee@6f930e0


When you compileEmployee.scala using scalac Employee.scala and convert it into Java code using javap Employee.class, it will generate the following code:

Compiled from "Employee.scala"
public class Employee {
  public Employee(int, java.lang.String, double); //java parameterized constructor.
  public Employee();   // java default constructor.
}


Now, you need to create a Scala class with a primary constructor and multiple auxiliary constructors:

scala> class Employee(empId: Int,name: String,salary :Double){
| def this(empId:Int,name:String)
| {
| this(0,"",0.0) // here it invokes primary constructor.
| println("Two-argument auxiliary constructor")
| }
| def this(empId:Int)
| {
| this(0,"",0.0) // here it invokes primary constructor.
| println("One-argument auxiliary constructor")
| }
| def this()
| {
| this(0) // here it invokes one-argument auxiliary constructor.
| println("Zero-argument auxiliary constructor")
| }
| println("Primary construtor")
| }
defined class Employee

scala> val emp = new Employee()
Primary construtor
One-argument auxiliary constructor
Zero-argument auxiliary constructor
emp: Employee = Employee@291a4791


In the above output, we created an instance with the help of the zero-argument auxiliary constructor. Zero-argument constructors call to one argument auxiliary constructor and one argument constructor to a primary constructor. Therefore, the primary constructor body would be executed first. Then, the one argument constructor body would be executed, followed by the zero-argument. Now, we will have code that looks like this:

scala> val emp = new Employee(101,"John")
Primary construtor
Two-argument auxiliary constructor
emp: Employee = Employee@37e69c43


When you invoke more than one time this in the auxiliary constructor, then it will invoke  apply()  in the class:

scala> class Point(x: Int,y: Int) {
| def this(x: Int) {
| this(x,5)
| println("auxiliary constructor")
| this(x,5);  // it will invokes object's apply method like this.apply(x,5).
| }
| def apply(x:Int,y:Int) = println(s" x= $x and y = $y")
| }
defined class Point

scala> val point = new Point(10)
auxiliary constructor
x= 10 and y = 5
point: Point = Point@310b2b6f


If an apply method does not get define in the class and call this more than one time in the auxiliary constructor, then it will give a compile time error:

scala> class Point(x: Int,y: Int) {
| def this(x: Int) {
| this(x,5)
| println("auxiliary constructor")
| this(x,5)
| }
| }
:15: error: Point does not take parameters
this(x,5)                                                                                                                                1                                scala> class Point(x: Int,y: Int) {                              2                                | def this(x: Int) {                              3                                | this(x,5)                              4                                | println("auxiliary constructor")                              5                                | this(x,5)                              6                                | }                              7                                | }                              8                                :15: error: Point does not take parameters                              9                

 

In Scala, we can also create a primary constructor with a default value. If you don’t provide value, then it will take the default value, which is provided in the primary constructor.  Otherwise, the value we provide is from an instance created with the help of a parameter name of the class. Here is an example:

scala> class Employee(empId: Int = 0,name: String = "",salary :Double = 0.0){
| println(s"empId = $empId , empName = $name , salary = $salary")
| }
defined class Employee

scala> val emp = new Employee()
empId = 0 , empName = , salary = 0.0
emp: Employee = Employee@713999c2

scala> val emp1 = new Employee(name = "Smith")
empId = 0 , empName = Smith , salary = 0.0
emp1: Employee = Employee@6be766d1

scala> val emp1 = new Employee(name = "Smith", empId = 9)
empId = 9 , empName = Smith , salary = 0.0
emp1: Employee = Employee@5ddb302


If we provide a wrong parameter name of the class at the time of instance creation, then it will give the compile-time error:

scala> val emp1 = new Employee(name = "Smith", empIf = 9)
:13: error: unknown parameter name: empIf
val emp1 = new Employee(name = "Smith", empIf = 9)                                                                                                                                1                                scala> val emp1 = new Employee(name = "Smith", empIf = 9)                              2                                :13: error: unknown parameter name: empIf                              3                                val emp1 = new Employee(name = "Smith", empIf = 9)                                                    

 

Please leave a comment below, if you have any questions or suggestions. Thanks!

Scala (programming language)

Published at DZone with permission of Randhir Singh. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • REST vs. Messaging for Microservices
  • How to Submit a Post to DZone
  • HTTP vs Messaging for Microservices Communications
  • Application Architecture Design Principles

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: