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