Scala – Getters and Setters

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

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

scala> a.size=(2)

scala> println(a.size)

use case 2:

scala> class Bigdata{

      var size = 2


scala> val x = new Bigdata

scala> 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

     scala> a.age = (2)

     scala> println(a.age)

Quick Support

image image