
- 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 - 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 Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- 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 - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - Companion Objects
This chapter takes you through the concept of companion objects in Scala programming. Companion objects are objects that share the same name as a class and are defined in the same source file. These can access the private fields and methods of their companion class. So, provide a way to associate static-like functionality with the class.
Companion Objects
Companion object is a singleton object. It has the same name as the class name and is defined in the same source file. Companion objects can access the private fields and methods of their companion class.
Syntax
The syntax of the companion objects are -
class ClassName { // Class fields and methods } object ClassName { // Companion object fields and methods }
Example
The following example shows a simple companion object in Scala programming.
class Circle(val radius: Double) { def area: Double = Circle.Pi * radius * radius } object Circle { val Pi: Double = 3.14159 def apply(radius: Double): Circle = new Circle(radius) } object Demo { def main(args: Array[String]) = { val circle = Circle(5.0) println(s"Circle radius: ${circle.radius}") println(s"Circle area: ${circle.area}") } }
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
Circle radius: 5.0 Circle area: 78.53975
In the example, the Circle class has a method area. This method calculates the area of the circle using the constant Pi defined in its companion object. The companion object Circle also defines an apply method. This is factory method to create instances of the Circle class. The Demo object has the main method.
Accessing Private Fields Using Companion Objects
Companion objects can access the private fields and methods of their companion class. So you can close interaction between the class and its companion object.
Example
The following example shows how a companion object can access private fields of its companion class.
class BankAccount(private var balance: Double) { def deposit(amount: Double): Unit = { if (amount > 0) balance += amount } def currentBalance: Double = balance } object BankAccount { def apply(initialBalance: Double): BankAccount = new BankAccount(initialBalance) def reset(account: BankAccount): Unit = { account.balance = 0 // Accessing private field of the companion class } } object Demo { def main(args: Array[String]) = { val account = BankAccount(1000.0) println(s"Initial balance: ${account.currentBalance}") account.deposit(500.0) println(s"Balance after deposit: ${account.currentBalance}") BankAccount.reset(account) println(s"Balance after reset: ${account.currentBalance}") } }
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
Initial balance: 1000.0 Balance after deposit: 1500.0 Balance after reset: 0.0
In the example, the BankAccount class has a private field balance and methods to modify it. The companion object BankAccount defines a reset method. This method can access and modify the private field balance of the BankAccount class. The Demo object uses the BankAccount class and its companion object.
Companion Objects for Utility Methods
Companion objects are used to define utility methods. These methods are logically related to the class but do not require an instance of the class to be accessed.
Example
class Temperature(val celsius: Double) { def toFahrenheit: Double = Temperature.celsiusToFahrenheit(celsius) } object Temperature { def celsiusToFahrenheit(celsius: Double): Double = celsius * 9 / 5 + 32 def fahrenheitToCelsius(fahrenheit: Double): Double = (fahrenheit - 32) * 5 / 9 } object Demo { def main(args: Array[String]) = { val temp = new Temperature(25) println(s"Temperature in Celsius: ${temp.celsius}") println(s"Temperature in Fahrenheit: ${temp.toFahrenheit}") println(s"50 Fahrenheit in Celsius: ${Temperature.fahrenheitToCelsius(50)}") } }
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
Temperature in Celsius: 25.0 Temperature in Fahrenheit: 77.0 50 Fahrenheit in Celsius: 10.0
In the example, the Temperature class represents a temperature in Celsius. It also has a method toFahrenheit that converts the temperature to Fahrenheit using a method defined in its companion object. The companion object Temperature defines utility methods for temperature conversion. The Demo object uses the Temperature class and its companion object.
Companion Objects for Factory Methods
Companion objects can define factory methods that create instances of the class. This approach provides more flexibility and can encapsulate creation logic.
Example
class Person(val name: String, val age: Int) // Define the Person class class Person(val name: String, val age: Int) // Companion object for Person object Person { def apply(name: String, age: Int): Person = new Person(name, age) def apply(name: String): Person = new Person(name, 0) // Default age to 0 } object Demo { def main(args: Array[String]) = { val person1 = Person("Alice", 30) val person2 = Person("Bob") println(s"Person1: ${person1.name}, Age: ${person1.age}") println(s"Person2: ${person2.name}, Age: ${person2.age}") } }
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
Person1: Alice, Age: 30 Person2: Bob, Age: 0
In the example,The Person class has two properties: name and age. It also has a companion object Person with apply methods for creating Person instances. The Demo object has the main method for creating Person objects and printing their details.
Scala Companion Objects Summary
- Companion objects are singleton objects. These have the same name as a class and are defined in the same source file.
- Companion objects can access the private fields and methods of their companion class.
- Companion objects are used in defining factory methods, utility functions, and constants related to the class.
- Companion objects provide a way to associate static-like functionality with a class.