As a next step, we'll add a method showing the width and height to the element, shown in code 10.2. The height method returns the number of rows in the contents. The Width method returns the length of the first row, or zero if the element has no row records. (That is, you cannot define an element with a height of zero but a width of zero.) )
Abstract class Element {
def Contents:array[string]
def height:int
= contents.length
def width:int = if (height = 0) 0 Else contents
(0). length
}
Code 10.2 defines a parameter-free method width and height
Note that the three methods of the element do not have a parameter list, not even a blank list. For example, instead:
def width (): Int
method is defined without parentheses:
def Width:int
This parameterless method is very common in Scala. In contrast, a method definition with an empty bracket, such as def height (): Int, is called an empty bracket method: Empty-paren methods. The recommended practice is to use a parameterless method when there are no parameters and the method accesses the mutable state only by reading the containing object (specifically, it does not change the mutable state). This Convention supports the unified Access principle: Uniform access Principle,meyer, object-oriented software constructs "Mey00" that means that client code should not be affected by the decision to implement a property through a field or method. For example, we can choose to use width and height as fields instead of methods, as long as we simply modify the Def to Val in each implementation:
Abstract class Element {
def Contents:array[string]
Val height =
contents.length
Val width =
if (height = 0) 0 Else contents
(0). length
}