Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Scala | Primary Constructor
Next article icon

Scala | Auxiliary Constructor

Last Updated : 17 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements (i.e. instructions). Statements are executed at the time of object creation. In Scala Program, the constructors other than the primary constructor are known as Auxiliary Constructors. We are allowed to create any number of auxiliary constructors in our Scala class, but a scala class contains only one primary constructor.
Auxiliary constructors are defined as methods in the class with the keyword this. We can describe multiple auxiliary constructors, but they must have different parameter lists.
Syntax : 
 

def this(......)


Let's try to understand Auxiliary constructors with help of some examples. 
Example #1: Using one Auxiliary Constructor 
 

Scala
// Scala program to illustrate the  // concept of Auxiliary Constructor   // Primary constructor  class GFG( Lname: String, Tname: String)  {      var no: Int = 0;;      def show()      {          println("Language name: " + Lname);          println("Topic name: " + Tname);          println("Total number of articles: " + no);               }           // Auxiliary Constructor      def this(Lname: String, Tname: String, no:Int)      {                   // Invoking primary constructor          this(Lname, Tname)          this.no = no      }  }   // Creating object object Main  {      // Main method     def main(args: Array[String])      {                   // Creating object of GFG class          var obj = new GFG("Scala", "Constructor", 4);          obj.show();      }  }  

Output: 
 

Language name: Scala Topic name: Constructor Total number of articles: 4


In above example, as we can see only one auxiliary constructor is used and primary constructor invoked in that auxiliary constructor. After creating object of GFG class(obj), show() function will be called and print the result. 
  
Example #2: Using more than one Auxiliary Constructor. 
 

scala
// Scala program to illustrate the  // concept of more than concept // Auxiliary Constructor   // Primary constructor  class Company  {     private var Cname = ""     private var Employee = 0        // Creating function     def show()      {          println("Language name: " + Cname);          println("Total number of employee: " + Employee);      }      // An auxiliary constructor     def this(Cname: String)     {          // Calls primary constructor         this()          this.Cname = Cname     }      // Another auxiliary constructor     def this(Cname: String, Employee: Int)      {            // Calls previous auxiliary constructor         this(Cname)          this.Employee = Employee     } }  // Creating object object Main  {      // Main method     def main(args: Array[String])      {          // Primary constructor         val c1 = new Company          c1.show()                  // First auxiliary constructor         val c2 = new Company("GeeksForGeeks")          c2.show()                  // Second auxiliary constructor         val c3 = new Company("GeeksForGeeks", 42)          c3.show()              }  }  

Output: 
 

Language name:  Total number of employee: 0 Language name: GeeksForGeeks Total number of employee: 0 Language name: GeeksForGeeks Total number of employee: 42


In above example, as we can see two auxiliary constructors are created with different parameters. Auxiliary constructor invoked primary constructor and another auxiliary constructor invoked previously defined auxiliary constructor.
 

Some Important Points About Auxiliary Constructor


 

  • In a single class, we are allowed to create one or more than one auxiliary constructors, but they have different signatures or parameter-lists.
  • Each auxiliary constructor must call one of the previously defined constructors, this would be primary constructor or previous auxiliary constructor.
  • The invoke constructor may be a primary or previous auxiliary constructor that comes textually before the calling constructor.
  • The first statement of the auxiliary constructor must contain this keyword.


 


Next Article
Scala | Primary Constructor

D

DivyaPareek
Improve
Article Tags :
  • Python
  • Scala
  • Scala-Constructor
Practice Tags :
  • python

Similar Reads

  • Scala Constructors
    Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. Scala supports two types of constructors: Primary Constructor When our Scala program contains only one c
    4 min read
  • Scala Constructs
    Some of the basic Scala constructs are expressions, blocks, classes, objects, functions, methods, traits, Main methods, fields, and closures. 1. Scala Expression: A computable statement in Scala is known as expression. For example, the following is an expression: 3 + 4. To print the output of an exp
    5 min read
  • Scala | Primary Constructor
    Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions). statements are executed at the time of object creation. When our Scala program contains only one constructor than that constructor is called a primary co
    4 min read
  • Calling A Super Class Constructor in Scala
    Prerequisite - Scala ConstructorsIn Scala, Constructors are used to initialize an object's state and are executed at the time of object creation. There is a single primary constructor and all the other constructors must ultimately chain into it. When we define a subclass in Scala, we control the sup
    3 min read
  • Scala Extractors
    In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and con
    6 min read
  • Scala | Product2
    Product2 is a trait in Scala, which is a Cartesian product of two elements. In build-in classes it can be considered as tuple of two elements. The Linear Supertypes here are Product, Equals, Any, and the sub-class here is Tulple2. Product2 extends Product like below: Product2[+T1, +T2] extends Produ
    2 min read
  • Scala | Product3
    Product3 is a trait in Scala, which is a Cartesian product of three elements. The Linear Supertypes here are Product, Equals, and Any and the known subclass here is Tuple3. It extends the trait Product i.e, trait Product3[+T1, +T2, +T3] extends Product Where, T1, T2, and T3 are the used parameter ty
    2 min read
  • Scala List +() operator with example
    The +() operator in Scala is utilized to append an element to the list. Method Definition: def +(elem: A): List[A] Return Type: It returns a list of the stated elements after appending it to an another element. Example #1: // Scala program of +() // method // Creating object object GfG { // Main met
    1 min read
  • Interesting fact about Scala
    Scala(pronounced as "skah-lah") is general-purpose programming language designed by Martin Odersky. The design of Scala started in 2001 at EPFL, Lausanne, Switzerland. Scala was released publicly in 2004 on Java platform. Scala is designed to be concise and addresses criticisms of Java. Scala source
    3 min read
  • Scala List ::() operator with example
    The ::() operator in Scala is utilized to add an element to the beginning of the List. Method Definition: def ::(x: A): List[A] Return Type: It returns the stated list after adding an element to the beginning of it. Example #1: // Scala program of ::() // method // Creating object object GfG { // Ma
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences