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.
Advertisements