Visbility of Class members in Scala
Scala programming model controls the visibility of class constructor arguments. Based on the declaration of the fields as val, var or private, the compiler generates the accessors and mutators accordingly.
The following matrix explains how the compiler generates the accessors and mutators of the class internally based on the declaration of the fields.
Val Fields
Assume if the class constructor is declared with Val fields, the value of the fields can be accessed but not changed. In general, the val declaration is meant for immutable fields. Thus Scala does not generate the mutator for the val fields.
class Person(val firstName: String, val lastName: String) { override def toString = s"$firstName $lastName" def printFullName{ println(this)} } object Test extends App{ var p = new Person("Murugan", "Shiva") p.printFullName p.firstName = "Ganesh" // Compiler error: reassignment to val p.printFullName }
Var Fields
The var fields are considered as a mutable fields. Hence, Scala generates appropriate Accessors and Mutators for the fields.
class Person(var firstName: String, var lastName: String) { override def toString = s"$firstName $lastName" def printFullName{ println(this)} } object Test extends App{ var p = new Person("Murugan", "Shiva") p.printFullName p.firstName = "Ganesh" p.printFullName }Then the output will look like,
Murugan Shiva Ganesh Shiva
Private fields
Declaring fields as private will make the fields non-accessible. Scala forbids to be generate getters and setters for private fields.
Exception in Case Class
Case class constructor parameters are quite different than normal class parameters. It considers the field as val by default.
case class Person(name:String) var p = new Person("Ram") p.name = "Lakshman" // Does not allow to reassign
Comments
Post a Comment