The Uniform Access Principle basically states that the notation used to access the object's member should be the same independent of whether the member is a field or a method. Thus the developer can remain ignorant of the actual implementation.
The Scala compiler automatically adds the getter/setter methods for constructor arguments depending on the type qualifier.
class Person(var name: String)
For the above class, the Scala compiler generates the following Java class which can be obtained after disassembling the Person.scala. You can clearly see that getter & setter methods have been added automatically
val person1 = new Person("Alice")
println(person1.name) // The getter is invoked here implicitly here
person1.name = "Bob" // The setter is invoked implicitly here
As is evident, the notation employed to access name field does NOT indicate whether the field is being accessed directly or the getter/setter method is being invoked. This is the Uniform Access Principle in action.
The Scala compiler automatically adds the getter/setter methods for constructor arguments depending on the type qualifier.
class Person(var name: String)
For the above class, the Scala compiler generates the following Java class which can be obtained after disassembling the Person.scala. You can clearly see that getter & setter methods have been added automatically
$ javap -p Person.class
Compiled from "Person.scala"
public class Person {
private java.lang.String name;
public java.lang.String name();
public void name_$eq(java.lang.String);
public Person(java.lang.String);
}
Note the special syntax for the setter which is suffixed with "_$eq". This allows the setter to be invoked when an assignment style syntax is employed:- If type = var, both getter/setter methods are added
- if type = val, only getter is added
- if no type is specified, neither getter/setter methods are added
val person1 = new Person("Alice")
println(person1.name) // The getter is invoked here implicitly here
person1.name = "Bob" // The setter is invoked implicitly here
As is evident, the notation employed to access name field does NOT indicate whether the field is being accessed directly or the getter/setter method is being invoked. This is the Uniform Access Principle in action.
No comments:
Post a Comment