overriding methods and fields for combining and inheriting

Source: Internet
Author: User

The fields and methods in the Blog,scala are the same namespaces, which allows the fields to override the parameterless method. For example, you can change the implementation of contents in the Arrayelement class from one method to a field without modifying the abstract method definition contents in the class element, as an example:

Abstract class Elements {def contents:array[string] val height = contents.length val width = if (height = = 0) 0 else contents (0). Length}
Class Arrayelement (conts:array[string]) extends Elements {//No lazy on the error, now do not understand why, first record the lazy Val Contents:array[stri NG] = Conts}object arrayelement {def main (args:array[string]): Unit = {val array = new Arrayelement (Array ("DD Daaa "," DDDWW ")) println (Array.width)}}

The contents field (defined by Val) in this version of Arrayelement provides a very good implementation for the parameterless method contents (defined with Def) in the element class (in scala2.10.7 version, why should we add lazy before the error? Do not add a null pointer exception!!! )。

Another way, Scala prohibits defining fields and methods in the same class with the same name. Although Java allows this to be done. example, this will not compile in the Scala class:

Class T2 {private var f = 0 def f = 1//cannot be compiled because the names of fields and methods}


overriding methods and fields for combining and inheriting

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.