Properties are easy to declare in Scala
class ShoePhone
{
var vibrateOn = false
var volume = 8
}
What does this really mean?
Here is the same code, written in a more cluttered way, illustrating the setters and getters which are automatically generated above
class ShoePhone
{
private[this] var _vibrateOn: Boolean = false;
private[this] var _volume: Int = 8;
def vibrateOn: Boolean = _vibrateOn;
def volume: Int = _volume;
def vibrateOn_=(on: Boolean)
{
_vibrateOn = on;
}
def volume_=(vol: Int)
{
_volume = vol;
}
}
Here the private fields are given names with an added underscore prefix. These names could be anything.
This is just a convention I'd like to see. I don't like seeing a lot of one-off names (such as the ones I used for the setter method parameters,
on
and
vol
). If there is a simple way to eliminate the one-off names akin to what one finds in the Java idiom
this.volume=volume;
please let me know.
The getter methods are defined without parentheses so they appear in code just as if they were fields. See
previous post on the Uniform Access principle.
The setter methods are defined by adding
_=
This suffix creates the method used when a variable is assigned using
=
Say we have a ShoePhone instance
shoePhone
and set its volume
shoePhone.volume = 0
You could write to the same effect
shoePhone.volume_=(0)
For an explanation of the access modifier
private[this]
see
The Scala cone of silence.