The ScalaKnol series attempts to share a nugget of Scala wisdom every few days or sometimes few times a day. Keep tuned. Today we would look at the Uniform Access Principle.
The principle states that the client code or the calling code should not be affected by the decision to implement an attribute as a field or a method. Hence essentially irrespective of whether the attribute is defined with a val or a def, the calling client should be agnostic of the same.
For example, if we have a class like
and we have the calling code like this
As always, you can see the output because we are coding in worksheet. Now suppose we have a change which results in the val salary now actually becoming a method. In this case let us assume that people whose name starts with a V get a higher salary. (Ok, I am biased, don’t curse your parents yet, because the bonus percentage goes down 😉
So, the new way to define our class then becomes something like this, and you would notice the change in the
If you notice, we did not change the client / calling code even though we changed the attribute from val to def. This is the Uniform Access Principle which Scala supports. Java on the other hand does not support this principle. If you recall, in Java we have array.length. Now string is also an array but for String we have to write string.length() because it is a method and not a field.