SCALA : Handling visibility of constructor fields


Constructor fields are parameters of class . In scala , we can define the visibility of parameters , visibility of parameters can be defined by “val” or “var” or without “val” or “var” .

For example : class Knoldus(val name:String)

Here, “val” defines the visibility of constructor field.

With val field

scala> class Knoldus(val name:String)
defined class Knoldus
scala> val knolObj=new Knoldus("Malti Yadav")
knolObj: Knoldus = Knoldus@59fc982f
scala> knolObj.name
res2: String = Malti Yadav
scala> knolObj.name="XYZ"
<console>:9: error: reassignment to val
knolObj.name="XYZ"
^

As we know that “val” is immutator so mutator method is not generated .In case of “val” field , we can not reassign value (scala> knolObj.name=”XYZ” ) .

With var field

scala> class Knoldus(var name:String)
defined class Knoldus
scala> val knolObj=new Knoldus("Malti Yadav")
knolObj: Knoldus = Knoldus@57391cbb
scala> knolObj.name
res0: String = Malti Yadav
scala> knolObj.name="XYZ"
knolObj.name: String = XYZ
scala> knolObj.name
res1: String = XYZ

In this case , we accessed the value and reassigned (mutated) the value because “var” is mutator .

Without val or val field

scala> class Knoldus(name:String)
defined class Knoldus
scala> val knolObj=new Knoldus("Malti Yadav")
knolObj: Knoldus = Knoldus@52efbabf
scala> knolObj.name
<console>:10: error: value name is not a member of Knoldus
knolObj.name
^

In this case , visibility of parameters are very restricted that why we can not access or set the value

Note : In “case class” , constructor fields are val by default .Case class rules are differ from above rules .

scala> case class Knoldus(name:String)
defined class Knoldus
scala> val knol=Knoldus("Malti Yadav")
knol: Knoldus = Knoldus(Malti Yadav)
scala> knol.name
res1: String = Malti Yadav
Advertisements

About Malti Yadav

An enthusiastic technologist , Scala developer, positive attitude and the desire to go extra mile .
This entry was posted in Scala. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s