Scala – Getters and Setters

  • date 22nd April, 2021 |
  • by Prwatech |
  • 0 Comments

Getters and Setters in Scala

 

A Getter and Setter in Scala are methods which helps in retrieving the value of variables and instantiate variables of class/trait respectively.

Getter are a procedure through which we get the value of the variables of a class.

Getting the worth of a global variable straightforwardly. In which we call indicate the name of the variable with the object.

Setter are a technique in which we can set the value of variables of a class.

use case 1:

scala> class Prwatech{

            var size = 1

            }

scala> val a = new Prwatech

2scala> a.size=(2)

scala> println(a.size)

use case 2:

scala> class Bigdata{

      var size = 2

      }

scala> val x = new Bigdata

2scala> x.size=(4)

scala> println(x.size)

//Getters and Setters can be redefined as explained below:

use case 3:

scala> class prwatech{

      private var privateAge = 0

      def age = privateAge

      def age_=  (newAge: Int) {if (newAge > privateAge) privateAge = newAge; }

      }

     scala> val a = new prwatech

     2scala> a.age = (2)

     scala> println(a.age)

 

In Scala, getters and setters are automatically generated for class fields using a concise syntax that promotes immutability and encapsulation. Unlike languages like Java, Scala encourages the use of immutable classes by default, reducing the need for explicit getters and setters. However, 

To define a field with custom , you can use the val or var keywords along with a custom method definition. For instance, a var field can be defined with custom getter and setter methods like def fieldName: FieldType = ... and def fieldName_=(value: FieldType): Unit = ....

 

Getters and Setters in Scala

0
0

Quick Support

image image