
- 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 - Singleton Object
We will discuss the concept of singleton objects in Scala programming in chapter. Singleton objects are unique instances of a class that cannot be instantiated more than once. These are used to represent global state and utility functions.
Singleton Objects in Scala
Singleton objects are created using the object keyword instead of class. Singleton objects can have methods and values that are shared across the entire application. It can also extend classes and traits, just like regular classes.
Syntax
The syntax of the singleton object is -
object SingletonName { // Fields and methods }
Example
The following example shows a simple singleton object in Scala programming.
object Greeting { def sayHello(name: String): Unit = { println(s"Hello, $name!") } } object Demo { def main(args: Array[String]) = { Greeting.sayHello("tutorialspoint") // Accessing the singleton object method } }
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
Hello, tutorialspoint!
In the example, the Greeting singleton object has method sayHello that prints a greeting message. The Demo object has the main method. It accesses the sayHello method of the Greeting singleton object.
Companion Objects
Companion object is a singleton object that shares the same name as a class. Companion object 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 is -
class ClassName { // Class fields and methods } object ClassName { // Companion object fields and methods }
Example
The following example shows the use of a companion object in Scala programming.
class Counter { private var count: Int = 0 def increment(): Unit = { count += 1 } def currentCount: Int = count } object Counter { def reset(counter: Counter): Unit = { counter.count = 0 // Accessing private field of the companion class } } object Demo { def main(args: Array[String]) = { val counter = new Counter counter.increment() counter.increment() println(s"Current count: ${counter.currentCount}") // Output: 2 Counter.reset(counter) println(s"Current count after reset: ${counter.currentCount}") // Output: 0 } }
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
Current count: 2 Current count after reset: 0
In the example, the Counter class has a private field count and methods to modify it. The companion object Counter defines a method reset that can access and modify the private field count of the Counter class. The Demo object uses the Counter class and its companion object.
Singleton Objects in Practice
Singleton objects are used to define utility methods and constants, manage global state, and implement the Singleton design pattern.
Example: Utility Methods
object MathUtils { def add(a: Int, b: Int): Int = a + b def subtract(a: Int, b: Int): Int = a - b } object Demo { def main(args: Array[String]) = { println(s"5 + 3 = ${MathUtils.add(5, 3)}") // Output: 8 println(s"5 - 3 = ${MathUtils.subtract(5, 3)}") // Output: 2 } }
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
5 + 3 = 8 5 - 3 = 2
Example: Global State
object Config { var applicationName: String = "Tutorialspoint" var version: String = "1.0.0" } object Demo { def main(args: Array[String]) = { println(s"Application Name: ${Config.applicationName}") println(s"Version: ${Config.version}") // Modify global state Config.version = "1.1.0" println(s"Updated Version: ${Config.version}") } }
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
Application Name: Tutorialspoint Version: 1.0.0 Updated Version: 1.1.0
Singleton Design Pattern
Singleton design pattern ensures that a class has only one instance and provides a global point of access to it. Singleton objects in Scala inherently follow this pattern.
Example
object Logger { def log(message: String): Unit = { println(s"Log: $message") } } object Demo { def main(args: Array[String]) = { Logger.log("This is a log message.") // Accessing the singleton object } }
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
Log: This is a log message.
In the example, the Logger singleton object has a log method that prints log messages. The Demo object uses the Logger singleton object.
Scala Singleton Object Summary
- Singleton objects are unique instances of a class. Singleton objects cannot be instantiated more than once.
- Singleton objects are defined using the object keyword.
- Companion objects share the same name as a class. Singleton objects can access the private fields and methods of their companion class.
- Singleton objects are useful for defining utility methods, managing global state, and implementing the Singleton design pattern.