The features in Scala

Source: Internet
Author: User
Tags traits

The traits in Scala are similar to those in Java, but the traits in Scala can have both abstract and concrete methods, and classes can implement multiple traits. Let's talk about the features of Scala in detail here.

1. Use the trait as an interface

We define a trait as follows:

1 trait Logger {2  def log (msg:string)3 }

It is important to note that methods that are not implemented in trait are abstract methods by default, so you do not need to add abstract to the method.

Subclasses Consolelogger the implementation of logger as follows:

1 class extends Logger {2   def log (msg:string): Unit = {3    println (msg)4    }5 }

There are two points to be aware of, one is to implement the extends instead of the implements, and the second is not to write the override keyword before the method.

When we need more than one trait, we can use the WITH keyword to add other traits, as shown here:

1 class extends Logger with cloneable with Serializable

We use the cloneable and serializable interfaces in the Java class Library as a trait, and it needs to be explained that all Java interfaces can be used as Scala traits.

2. Characteristics with specific implementation

Consolelogger traits with specific methods, as follows:

1 trait Logger {2   def log (msg:string): Unit = {3    println (msg) 4   }5 }

Now we call log () in the Consolelogger trait, as shown below:

 1  class  savingsaccount extends   account with Consolelogger { 2  def withdraw (amount:double): Unit = { 3
     if  (Amount > balance)  4  log ("insufficient funds" )  5  Span style= "color: #0000ff;" >else  6  balance-= amount  7   8   ...  9 } 

Essentially, the SavingsAccount class is mixed with the function of the consolelogger trait, but there is also a downside: when the trait changes, all classes that are mixed with that trait must be recompiled.

3. Objects with traits

We define the logged traits as follows:

1 trait logged {2   def log (msg:string): Unit = {3  }4 }

Although the logged trait takes a concrete approach to log (), the method does nothing.

We use the logged trait in class SavingsAccount, as follows:

 1  class  savingaccount "extends   account with logged { 2  def withdraw (amount:double): Unit = if  (Amount > balance)  4  log (" Insufficient funds ")  5  else  6  balance-= amount  7   8   ...  9 } 

It seems that the above code is meaningless, but we can mix a better implementation when constructing a specific object, as shown here:

1 extends logged {2   override def log (msg:string): Unit = {3    println (msg) C10>4  }5 }

We add the Consolelogger trait when constructing the object acct, as follows:

1 New SavingsAccount with Consolelogger

4. The qualities that are superimposed together

We can add multiple calls to each other for a class or object, and the call executes from the last trait. What is the use of this? It is primarily used for scenarios where a certain value needs to be processed in a phased process.

Let's say we want to add a timestamp to all the log messages, as follows:

1 New SavingsAccount with Consolelogger 2 3 extends logged {4   override def log (msg:string): Unit = {5     Super . log (new java.util.Data () + "+ msg)6  }7 }

Likewise, suppose we want to truncate the log messages that are too verbose, as follows:

1 extends logged {2   val maxLength =3  override deg log (msg:string) {4 c10/>Super. log (5       ifelse msg.substring (0, maxLength-3 ) +6         "...")7  }8 }

It is particularly important to note that Super.log does not have the same meaning as a class, and of course, if the meaning is the same, then these traits are useless, because the logged character of these traits extends nothing in the log (). In fact, Super.log invokes the next trait in the trait hierarchy, which is determined by the order in which the trait is added. We will use examples to illustrate the sequence of actions, as follows:

1 New SavingsAccount with Consolelogger with Timestamplogger with Shortlogger 2 New SavingsAccount with Consolelogger with Shortlogger with Timestamplogger

If we execute the first statement, we'll get the message. Sun Feb 17:45:45 ICT Insufficient ... This means that the log () in Shortlogger is executed first, and then its super.log is called Timestamplogger.

If we execute the second statement, we'll get the message. Sun Feb 06 1 ... this shows that the log () in Timestamplogger is executed first, and then its super.log is called Shortlogger, and the result is truncated later.

5. Overriding the abstract method in the trait

6. As a feature of rich interface use

7. Specific fields in the trait

8. Abstract fields in a trait

9. Trait Construction Sequence

10. Fields in the initialization trait

11. Characteristics of the Extended class

Reference documents:

[1] Get a quick look at the Scala technology stack: http://www.infoq.com/cn/articles/scala-technology/

[2] "Learn Scala fast"

[3] Fast learning Scala tenth features after class exercise solution: http://css.gxzj.com.cn/News.aspx?id=383960

The features in Scala

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.