
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Methods
- Scala - Functions
- Scala - Methods vs Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala - Polymorphic Functions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - NumericRange
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala Advanced Types
- Scala - Union Types
- Scala - Intersection Types
- Scala - Type Aliases
- Scala - Structural Types
- Scala - Match Expression
- Scala - Singleton Type Operator
- Scala - Abstract Types
- Scala - Dependent Types
- Scala - Abstract Type Bounds
- Scala - Higher-Kinded Types
- Scala - Opaque Type Alias
- Scala - Path-Dependent Types
- Scala - Type Lambdas
- Scala - Type Inference
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Guards
- Scala - Variables in Patterns
- Scala - Type Patterns
- Scala - The Matchable Trait
- Scala - Matching Arrays
- Scala - Matching Lists
- Scala - Matching Tuples
- Scala - Exception Handling
- Scala - Extractors
- Scala - Pattern Bindings
- Scala - Regular Expressions
- Scala - Case Classes
- Scala - Partial Functions
- Scala - Packaging and Imports
- Scala - Implicit Imports
- Scala - Export Clauses
- Scala - Nested Packages
- Scala - Chained Packages
- Scala - Package Objects
- Scala Files I/O
- Scala - Files I/O
- Scala - Writing Files
- Scala - Listing Files
- Scala - Deleting Directories
- Scala - Check File Exists
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Process Management
- Scala - Scaladoc
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala Unit Testing
- Scala - Unit Testing
- Scala - uTest
- Scala - MUnit
- Scala - ScalaTest Runner
- Scala - ScalaMock
- Scala - JUnit
- Scala - Mocking
- Scala - BDD Testing
Scala - Primary Constructor
A constructor in Scala is a special method used to initialize objects. There are two types of constructors in Scala: primary constructors and auxiliary constructors. Through constructors, you can set initial values for fields and execute any setup required when an object is created. This chapter explains how to use constructors in Scala programming.
Primary Constructors
The primary constructor is part of the class definition itself. It is used to initialize the fields of a class and can take parameters, which are typically used to initialize the fields of the class.
The primary constructor is the main constructor for a class and is defined as part of the class signature. It is executed when an object of the class is instantiated.
Syntax
class ClassName(parameter1: Type, parameter2: Type) { // Class body }
Example
The following example shows a simple primary constructor in Scala programming.
class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int): Unit = { x += dx y += dy } override def toString: String = s"Point($x, $y)" } object Demo { def main(args: Array[String]): Unit = { val point = new Point(10, 20) println(point) point.move(5, 5) println(point) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Point(10, 20) Point(15, 25)
In the example, the Point class has a primary constructor with parameters xc and yc. The Demo creates an instance of the Point class and calls its methods.
Primary Constructor with Default Parameters
You can define default values for constructor parameters. You can create objects by providing default values when some arguments are not supplied.
Syntax
class ClassName(parameter1: Type = defaultValue1, parameter2: Type = defaultValue2) { // Class body }
Example
The following example shows default parameters in primary constructors.
class Car(val brand: String = "Toyota", val model: String = "Corolla", val year: Int = 2020) { override def toString: String = s"Car(brand: $brand, model: $model, year: $year)" } object Demo { def main(args: Array[String]): Unit = { val car1 = new Car() val car2 = new Car("Honda", "Civic") val car3 = new Car("Ford", "Mustang", 2022) println(car1) println(car2) println(car3) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Car(brand: Toyota, model: Corolla, year: 2020) Car(brand: Honda, model: Civic, year: 2020) Car(brand: Ford, model: Mustang, year: 2022)
In the example, the Car class has a primary constructor with parameters that have default values. The Demo object creates instances of the Car class with and without specifying all the parameters.
Primary Constructor with Private Fields
You can use private keyword to make fields private in the primary constructor. It restricts access to these fields from outside the class.
Syntax
class ClassName(private val parameter1: Type, private val parameter2: Type) { // Class body }
Example
The following example shows a primary constructor with private fields.
class BankAccount(private val accountNumber: String, initialBalance: Double) { private var balance: Double = initialBalance def deposit(amount: Double): Unit = { balance += amount } def withdraw(amount: Double): Unit = { balance -= amount } def getBalance: Double = balance override def toString: String = s"BankAccount($accountNumber, $balance)" } object Demo { def main(args: Array[String]): Unit = { val account = new BankAccount("12345", 1000.0) println(account) account.deposit(500.0) account.withdraw(200.0) println(s"Balance: ${account.getBalance}") } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
BankAccount(12345, 1000.0) Balance: 1300.0
In the example, the BankAccount class has a primary constructor with private fields. The Demo object interacts with an instance of the BankAccount class through its public methods.
Primary Constructor with Initialization Code
The primary constructor can include initialization code in the class body. This code is executed when an object of the class is created.
Syntax
class ClassName(parameter1: Type, parameter2: Type) { // Initialization code // Class body }
Example
The following example shows initialization code in the primary constructor.
class Employee(val name: String, val age: Int) { println(s"Creating Employee: $name, $age") def displayInfo(): Unit = { println(s"Employee Name: $name, Age: $age") } } object Demo { def main(args: Array[String]): Unit = { val employee = new Employee("Alice", 30) employee.displayInfo() } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Creating Employee: Alice, 30 Employee Name: Alice, Age: 30
In the example, the Employee class includes initialization code that prints a message when an object is created. The Demo object creates an instance of the Employee class and calls its methods.
Scala Primary Constructor Summary
- The primary constructor in Scala is defined as part of the class signature. It is executed when an object is created.
- Default parameters can simplify object creation by providing default values when some arguments are not supplied.
- Fields in the primary constructor can be made private to restrict access from outside the class.
- The primary constructor can include initialization code in the class body, which is executed when an object is created.