Overloaded Methods and fields
The unified access principle is just one aspect of Scala's more unified approach to fields and methods than Java. Another difference is Scala, where fields and methods belong to the same namespace. This makes it possible to overload the field with a parameterless method. For example, you can change the implementation of a contents in a class arrayelement from one method to a field without having to modify the contents abstract method definition in the class element, as shown in code 10.4:
Class Arrayelement (conts:
array[string]) extends Element {
val contents:array[string] = conts
}
Code 10.4 parameter-free method with field overload
In this arrayelement version, the field contents (defined by Val) perfectly implements the parameterless method contents (defined in Def) in the class element.
On the other hand, Scala prohibits defining fields and methods in the same class with the same name, which is allowed in Java. For example, the following Java class can be well compiled:
Code
class Compilesfine {
private int f = 0 in Java; public
int F () {return
1;
}
}
But the corresponding Scala class will not compile:
Class Wontcompile {
private var f = 0//Compilation However, because field and method duplicate
def f = 1
}
Typically, Scala prepares only two namespaces for definitions, compared to four java. Java's four namespaces are fields, methods, types, and packages. In contrast, Scala's two namespaces are:
values (fields, methods, packages, and a single Instance object)
type (class and trait name)
Scala's reason for putting fields and methods into the same namespace is clear, because you can use Val to overload the parameterless method, something you can't do in Java. In Scala, the package shares the same namespaces as fields and methods so that you can directly reference the package in addition to simply referencing the type name and the fields and methods of the single Instance object. This is also what you can't do in Java.