5-scala object (Class) and Class (object)

Source: Internet
Author: User
Tags abstract anonymous class definition constructor modifier modifiers require traits

Class and constructors:
The class is defined as follows:

Class MyClass (A:int, b:int) {
    println (a.tostring)
}

In Scala, classes can also have class parameters, class parameters can be used directly in the body of the class, there is no need to define a field and then assign the constructor parameters to the field, but it should be noted that: the class parameter is just a parameter, not a field, if you need to use elsewhere, you must define the field. There is, however, a definition of a parameterized field, which can be defined as a simplified characters segment, as follows:

Class MyClass (Val a:int, Val b:int) {
    println (a.tostring)
}

The above code has a Val declaration that defines class fields while defining class parameters, but they use the same name. Class parameters can also be prefixed with Var, with private, protected, override modifiers, and so on. The Scala compiler collects the class parameters and creates the main constructor of the class with the same parameters, and compiles any code inside the class that is neither a field nor a method definition into the main constructor. In addition to the main constructor, Scala can also have an auxiliary constructor, which is defined as the Def this (...). Each auxiliary constructor is "this (...)" In the form of a call to other constructors in this class, the called constructor can be either the primary constructor or the other auxiliary constructors in the source file that are earlier than the call to the constructor definition. The result is that the call to the Scala constructor will eventually result in a call to the main constructor, so the primary constructor is the only entry point for the class. In Scala, only the main constructor can call the superclass's constructor.
You can add the Private keyword before the class argument list so that the class's main constructor is private, and the private primary constructor can be accessed only by the class itself and the associated object.
You can use the Require method to add prerequisites to the constructor's parameters, and require throws an exception to prevent the object from being created if it does not meet the requirements.
If the body of the class is empty, you can omit the curly braces.
Access Level control:

Public is the default access level for Scala, so do not specify any access modifiers if you want to make members public. Members of the public can be accessed from anywhere.

Private is similar to Java, which is preceded with private. The difference is that outside classes in Scala do not have access to private members of inner classes.

Protection is similar to Java, which is preceded by protected. The difference is that other classes in the same package in Scala cannot access the protected members.

Access modifiers in Scala can be emphasized by using qualifiers. A modifier in the format private[x] or protected[x] means "until X" is private or protected, where x refers to a package, class, or singleton object that belongs to.

Scala also has a more restrictive access modifier than private, which is private[this]. The definition of a private[this] tag can only be accessed in the same object that contains the definition, which is called the object's private. This guarantees that members are not accessible to other objects in the same class.
For private or protected access, Scala's access rules give the associated object and class some privileges, and the associated object can access all of its associated classes ' private members, protect members, and vice versa.
Members (types, fields, and methods):
Type members can also be defined in Scala, and type members are declared with the keyword type. By using type members, you can define aliases for types.
Scala fields and methods belong to the same namespace, Scala prohibits defining fields and methods in the same class with the same name, although Java allows this.
Getter and setter:
In Scala, each non-private VAR member variable of a class implicitly defines the getter and setter methods, but their naming does not follow the Java conventions, and the Getter method of the Var variable x is named "X", and its setter method is named "X_=". You can also define the appropriate getter and setter methods when you need them, and you can also do this by not defining the associated fields, and one of the benefits of customizing the setter is that you can check the validity of the assignment.
If you label the Scala field as @beanproperty, the Scala compiler automatically adds additional getter and setter methods that conform to the JavaBeans specification, such as getxxx/setxxx. In this way, it facilitates interoperability between Java and Scala.

Sample class:

The class with the case modifier is called the Sample class (case Class), which allows the Scala compiler to automatically add syntactic convenience settings to your class for pattern matching, and the Scala compiler automatically adds the following syntax:
To help you implement a companion object of this class, and provide the Apply method in the associated object, so that you can construct the corresponding object without the new keyword;
The Unapply method is provided in the companion object to allow the pattern matching to work;
All parameters in the sample class parameter list implicitly obtain the Val prefix, so they are maintained as a field;
Add the "natural" implementation of ToString, hashcode, equals, copy.

Closed class

A class with the sealed modifier is called the enclosing class (sealed Class), and the enclosing class cannot add any new subclasses in addition to the file where the class definition resides. This is useful for pattern matching because it means that you only need to care about the subclasses you already know. This also means that you can get better compiler help.

Single-instance objects

Scala does not have a static method, but it has a similar feature, called a singleton object, defined in the Object keyword (Note: The main function should also be defined in object, and any singleton object with a proper signature of the Main method can be used as the entry point for the program). Defining a singleton object does not mean that you have defined the class, so you cannot use it to new objects. When a singleton object shares the same name as a class, it is called a companion object of the Class (companion. The class and its associated objects must be defined in the same source file. The class is referred to as the companion class for this singleton object. The class and its associated objects can access each other's private members. Singleton objects that do not share names with the associated class are called stand-alone objects (standalone object).
Apply vs. Update: In Scala, syntax similar to function calls is typically used. When you pass a variable to an object using parentheses, Scala converts it to the invocation of the Apply method, assuming that the type actually defines the Apply method. For example, S is a string, then S (i) is equivalent to s[i in C + +] and Java S.charat (i), in fact, S (i) is a shorthand for s.apply (i). Similarly, BigInt ("123") is the shorthand for bigint.apply ("123"), which uses the associated object BigInt's apply method to produce a new BigInt object without using new. Similarly, when assigning a value to a variable with parentheses and one to several arguments, the compiler uses the object's Update method to make a call to the argument (index value) in parentheses and to the object to the right of the equals sign, such as arr (0) = "Hello", which is converted to Arr.update (0, "Hello" )。
The difference between a class and a singleton object is that the singleton object has no arguments, and the class can. Because the Singleton object is not instantiated with the new keyword, there is no chance of passing it to the instantiated parameter. Singleton objects are initialized the first time they are accessed. When you instantiate an object, if you use new, the object is instantiated with the class, and no new is generated with the associated object. Also note that we can nest and define other classes and (singleton) objects in a class or (singleton) object.

Equality of objects

Unlike Java, in Scala, "= =" and "! =" can be used directly to compare the equality of objects, and the "= =" and "! =" Methods call the Equals method, so you generally need to override the Equals method. If you want to determine if the reference is equal, you can use the EQ and NE.
When using a container class library with a hash structure, we need to overwrite both the hashcode and the Equals method, but implementing a correct hashcode and equals method is a difficult thing, and you need to consider a lot of questions and details, which can be found in the corresponding section of the Java summary. Also, as the sample class section says, once a class is declared as a sample class, the Scala compiler will automatically add the correct hashcode and equals methods to match the requirements.

Abstract classes and abstract members
Like Java, the classes that are declared in Scala are abstract classes, and abstract classes cannot be instantiated.
In Scala, methods, fields, and types in abstract classes and traits can be abstract. Examples are as follows:

        Trait Myabstract {
            type T               //abstract type
            def transform (x:t): T   //abstract method
            val initial:t           //abstract Val
            var c Urrent:t          //abstract var
        }

Abstract Methods : Abstract methods do not need (and do not allow) an abstract modifier, and a method that is not implemented (without an equal sign or a method body) is abstracted.
abstract Type : A type member in Scala can also be abstract. Abstract types do not mean that a class or trait is abstract (the trait itself is abstract), and that the abstract type is always a member of a class or trait.
abstract Field : a Val or Var member that is not initialized is abstract and you need to specify its type at this point. Abstract fields sometimes play roles similar to superclass parameters, which are especially important for traits, because the trait lacks a constructor that can be used to pass parameters. So the parametric trait is done by implementing an abstract field in the subclass. For the following qualities:

Trait Myabstract {
            val test:int
            println (test)
            def show () {
                println (test)
            }
}

You can use the following anonymous class syntax to create an instance of an anonymous class that inherits from that trait, as follows:

New Myabstract {
            val test = 1
        }.show ()

You can parameterize the traits in the above way, but you will find that this is different from the "new class name (parameter list)" Parameterization of a class instance, because you see two println for the test variable (the first time in the trait body, the second is because method show is called), The output is two different values (the first is 0, the second is 1). This is mainly because the superclass is initialized before the subclass, and the specific implementation of the superclass abstract member in the subclass is initialized in the subclass. To solve this problem, you can use pre-initialized fields and lazy values.
Pre-initialize fields:

      Class B extends {
            val a = 1
        } with a

The pre-initialization fields are used for anonymous classes in the following form:

      New {
            val a = 1
        } with a

It is important to note that because pre-initialized fields are initialized before the superclass constructor is called, their initializers cannot reference the object being constructed.
Lazy Value :
The Val variable with the lazy modifier is called the lazy value, and the expression on the right side of the lazy value is calculated only when the lazy value is first used. If the initialization of lazy values does not cause side effects, then the order of lazy definitions is not considered, because initialization is on-demand.

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.