
- 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 - Object Private Fields
We will explain the concept of private fields in Scala objects in this chapter. Private fields restrict access to object internal state. So, these can only be accessed and modified within the object itself and within the defining class. This encapsulation provides data hiding and maintains the integrity state of the object.
Private Fields
Private fields are variables. These are declared within a class and object that cannot be accessed directly from outside the class. In Scala, you can define private fields using the private keyword.
Syntax
The syntax of the private field is -
class ClassName { private var fieldName: Type = initialValue }
Example
The following example shows how to define and use private fields in Scala programming.
class Point { private var _x: Int = 0 private var _y: Int = 0 def x: Int = _x // Getter def x_=(value: Int): Unit = { _x = value } // Setter def y: Int = _y // Getter def y_=(value: Int): Unit = { _y = value } // Setter def display(): Unit = { println(s"Point x location: $x") println(s"Point y location: $y") } } object Demo { def main(args: Array[String]) = { val pt = new Point pt.x = 10 pt.y = 20 pt.display() } }
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 x location: 10 Point y location: 20
In the example, the Point class has private fields _x and _y. These fields are accessed and modified through public getter and setter methods (x, x_=, y, and y_=). These control access to the private fields. The display method prints the values of x and y.
Access Modifiers
Access modifiers in Scala control the visibility of classes, traits, objects, and members. The private modifier restricts access to the defining class and object.
Syntax
The syntax of the private field is -
class ClassName { private var fieldName: Type = initialValue def methodName(): Type = { // Access private field fieldName } }
Example
The following example shows the use of private fields with access modifiers in Scala.
class Rectangle { private var _width: Double = 0.0 private var _height: Double = 0.0 def width: Double = _width // Getter def width_=(value: Double): Unit = { // Setter if (value > 0) _width = value else println("Width must be positive") } def height: Double = _height // Getter def height_=(value: Double): Unit = { // Setter if (value > 0) _height = value else println("Height must be positive") } def area: Double = _width * _height def display(): Unit = { println(s"Rectangle width: $width") println(s"Rectangle height: $height") println(s"Rectangle area: $area") } } object Demo { def main(args: Array[String]) = { val rect = new Rectangle rect.width = 5.0 rect.height = 4.0 rect.display() rect.width = -3.0 // Attempt to set a negative width rect.display() } }
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
Rectangle width: 5.0 Rectangle height: 4.0 Rectangle area: 20.0 Width must be positive Rectangle width: 5.0 Rectangle height: 4.0 Rectangle area: 20.0
In the example, the Rectangle class has private fields _width and _height. These fields are accessed and modified using public getter and setter methods with validation logic. The display method prints the values of width, height, and area.
Private Fields in Companion Objects
Companion objects in Scala can access the private fields and methods of their companion classes. So, there is a clean separation of logic while maintaining encapsulation.
Syntax
The syntax is -
class ClassName { private var fieldName: Type = initialValue } object ClassName { def methodName(instance: ClassName): Type = { // Access private field of the companion class instance.fieldName } }
Example
The following example shows the use of private fields in companion objects 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 // Access 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. The companion object Counter has a method reset. This method accesses and modifies the private field count of the companion class. The Demo object uses the Counter class and its companion object.
Scala Object Private Fields Summary
- Private fields restrict access to the object internal state. So, it provides encapsulation and data hiding.
- Access modifiers in Scala control the visibility of classes, traits, objects, and members.
- Getters and setters provide controlled access to private fields. So fields are accessed and modified in a controlled manner.
- Companion objects can access private fields and methods of their companion classes. So there is a clean separation of logic while maintaining encapsulation.