How to learn in Scala 12-fields, methods, and constructors

Source: Internet
Author: User

In the previous section, a Scala class was created, and if there are no more methods, the definition of the Scala class can be simpler, take a look at the following definition of the CreditCard class:

class CreditCard (Val Number:int, var creditlimit:int)

Yes, the definition of the class is completed in one line and no curly braces are required.

Because Scala is also running on the JVM, consider Java as a way to look at the compiled class file. The way to view is still flexible, you can use Jd-gui, you can use the Javap–private creditcard command, and there is an online anti-compilation site Showmycode. Post-compilation Java code:

 Public classCreditCard { Public intNumber () {returnNumber ; }   Public intCreditlimit () {returnCreditlimit; }   Public voidCreditlimit_$eq (intX$1) {Creditlimit= x$1; }   PublicCreditCard (intNumberintcreditlimit) {     This. Number =Number ;  This. Creditlimit =Creditlimit; Super (); }  Private Final intNumber ; Private intCreditlimit;}

A good long Java code. First Scala converts the CreditCard class to public by default. Since number is declared as Val in Creditcard.scala, number is defined as final in the Java code generated by the decompile. In addition, you can see a constructor in the compiled code and a method for reading and writing member variables. You can see that the getter and setter of member variables are somewhat inconsistent with the naming methods we are accustomed to using in Java. Also, because number has a final modifier, there is no setter method for it. If the definition symbol for a member variable in Scala is neither Var nor Val, then Scala creates a private field and private getter and setter methods for it, and therefore cannot access the member variable outside of the class.

All executable statements or expressions placed in a class definition are considered to be part of the constructor of the class. The following code is an example:

class Sample {  println ("Constructing an instance of sample")}new sample

In this code, we first define a class sample, and then create an instance of the sample class to perform a look:

The print statement in the class definition is output when the instance is created because the print statement is part of the constructor.

In addition to providing member variables in the main constructor, we can also define other fields, methods, 0 or more secondary constructors within a class. In the following class, you define a member variable position, a secondary constructor, this (), and the ToString () method is overridden in the class.

classPerson (Val firstname:string, Val lastname:string) {Privatevar position:string =_ println ("Creating" +toString ()) def This(firstname:string, lastname:string, positionheld:string) { This(FirstName, lastName) position=Positionheld} override def toString (): String={firstName+ "" + LastName + "holds" + position + "position"}}val John=NewPerson ("John", "Smith", "Analyst") println (John) Val Bill=NewPerson ("Bill", "Walker") println (Bill)

The result of executing the code is as follows:

A little attention is paid to the implementation of the secondary constructor: if there is a primary constructor, then the first line of the secondary constructor must be a call to the main constructor or other secondary constructor. This is somewhat similar to when Java inherits from the parent class.

Also worth noting is the definition of member variable position, take this line alone to see it:

private var position:string = _

The first interesting thing is the initialization assignment, which is an "_"-underline. Here "_" stands for the default value of the corresponding type. for int, its value is 0; for double, its value is 0.0; for string, its value is null. By using "_", it is convenient to set the initial default value for the VAR member variable. You cannot use "_" for Val members, however, because Val members do not allow modification, you must explicitly specify an initial value

By looking at the Java class of Person.scala's bytecode decompile, you can see that the Scalac compiler sets the getter and setter methods by default for the member variable position (although not set in the way we used to JavaBean). The visibility of member variables defined in Scala is controlled by the access rights of getter and setter methods in the Decompile Java code.

If you prefer traditional javabean annotations, you can add annotation @beanproperty when the member variable is defined:

@BeanProperty  var position:string = _

Remember to import annotations before declaring them. However, there is a limit to this: member variables cannot be declared private at this time. And this will only generate additional two JavaBean getter and setter, the original getter and setter will continue to be retained. This can be verified with javap–private after compiling the person class:

That's it.

#######

How to learn in Scala 12-fields, methods, and constructors

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.