
- 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 - Getters and Setters
This chapter takes you through the concept of getters and setters in Scala programming. Getters and setters are methods that control access to fields of an object. These methods can be defined explicitly. You can also use Scala built-in support for properties to automatically generate these.
Getters in Scala
Getter is a method that you can access the value of a private field in a class. It is defined using the def keyword and should return the value of the field it is accessing.
Syntax
The syntax of the getters are -
class ClassName { private var _field: Type = initialValue def field: Type = _field // Getter }
Example
The following example shows a simple getter in Scala programming.
class Point { private var _x: Int = 0 private var _y: Int = 0 def x: Int = _x // Getter def y: Int = _y // Getter 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 println(s"x: ${pt.x}, y: ${pt.y}") 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
x: 0, y: 0 Point x location: 0 Point y location: 0
In the example, the Point class has private fields _x and _y. The getters x and y are defined to access these fields. The display method prints the values of x and y.
Setters in Scala
Setter is a method that you can modify the value of a private field in a class. It is typically defined using the def keyword with a special syntax. The method name followed by _= and takes a parameter that represents the new value for the field.
Syntax
The syntax of the setters is -
class ClassName { private var _field: Type = initialValue def field_=(value: Type): Unit = { _field = value } // Setter }
Example
The following example shows a simple setter in Scala.
class Point { private var _x: Int = 0 private var _y: Int = 0 // Getter methods def x: Int = _x def y: Int = _y // Setter methods def x_=(value: Int): Unit = { _x = value } def y_=(value: Int): Unit = { _y = value } def display(): Unit = { println(s"Point x location: $_x") println(s"Point y location: $_y") } } object Demo { def main(args: Array[String]): Unit = { 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. The setters x_= and y_= are defined to modify these fields. The display method prints the updated values of _x and _y.
Automatic Getters and Setters
In Scala, you can also define getters and setters using val and var. When you define field with val, Scala generates getter for you. When you use var, Scala generates both getter and setter.
Syntax
class ClassName { val field1: Type = initialValue // Generates only a getter var field2: Type = initialValue // Generates both getter and setter }
Example
The following example shows the use of val and var to automatically generate getters and setters in Scala programming.
class Circle(val radius: Double) { // Only getter for radius var color: String = "red" // Getter and setter for color def display(): Unit = { println(s"Circle radius: $radius") println(s"Circle color: $color") } } object Demo { def main(args: Array[String]) = { val circle = new Circle(5.0) circle.color = "blue" circle.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
Circle radius: 5.0 Circle color: blue
In the example, the Circle class has val field radius and var field color. Scala automatically generates getter for radius and both getter and setter for color. The display method prints the values of radius and color.
Custom Getters and Setters
You can add more logic using custom getters and setters in Scala. For example, validation, when accessing or modifying fields. This provides more control over how fields are accessed and updated.
Example
The following example shows custom getters and setters with validation logic.
class Rectangle { private var _width: Double = 0.0 private var _height: Double = 0.0 def width: Double = _width // Custom Getter def width_=(value: Double): Unit = { // Custom Setter if (value > 0) _width = value else println("Width must be positive") } def height: Double = _height // Custom Getter def height_=(value: Double): Unit = { // Custom 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 custom getters and setters for _width and _height. The setters include validation logic for positive values. The display method prints the values of width, height, and area.
Scala Getters and Setters Summary
- Getters and setters provide controlled access to the field of objects. Hence encapsulation and data hiding are possible here.
- Scala automatically generates getters and setters for val and var fields.
- You can add more logic using custom getters and setters, like validation, when accessing and modifying fields.
- You can improve code readability and maintainability using getters and setters.