Define a parameterless method in Scala

Source: Internet
Author: User

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
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.