Getting started with Scala-the tenth section of Scala class hierarchy, traits preliminary

Source: Internet
Author: User
Tags traits

The main contents of this section
    1. Scala class Hierarchy Overview
    2. How to implement the native type of Scala
    3. Nothing, NULL type resolution
    4. Traits Introduction
    5. Traits several different ways to use
1 Scala class hierarchies

The class hierarchy chart in Scala is as follows:


Source: Programming in Scala

As you can see from the class hierarchy diagram above, the any class at the top of the inheritance hierarchy is the root class that Scala inherits, and all of the classes in Scala are its subclasses
The following methods are defined in the Any class:

//==与!=被声明为final,它们不能被子类重写finaldef ==(that: Any): Booleanfinaldef !=(that: Any): Booleandef equals(that: Any): Booleandef hashCode: Intdef toString: String

As you can see from the code above, the any class includes five methods, where = = and! = are declared as final types, so they cannot be overridden by the quilt class, in fact the real implementation of = = is implemented by the Equals method, and! = is implemented by!equals, so if you want to change = = with the! = Method behavior, you can override equals directly.

The root class any has two subclasses, each of which is anyval and Anyref, where Anyval is all Scala built-in value types (Byte, short, Char, Int, Long, Float, Double, Boolean, The parent class of Unit.), where Byte, short, Char, Int, Long, Float, Double, Boolean, and Byte,short,char,int,long,float,double in Java The Boolean primitive type corresponds, and the Unit corresponds to the void type in Java, because (Byte, short, Char, Int, Long, Float, Double, Boolean, Unit) inherits Anyval, and Anyval inherits any , so they can also invoke methods such as ToString.

2.0.hashCoderes5:10737418242.0 toStringres6:2.0

It is worth mentioning that () can be used as an instance of the unit type, it can also call ToString and other methods

`==‘ will always yield true              ()==()                ^res9: Boolean = true

Anyref is another subclass of any that is the parent of all non-value types in Scala, corresponding to the Java.lang.Object class (which can be thought of as the alias of the Java.lang.Object Class), which is the parent class of all reference types (except for value types). So why not just Java.lang.Object as the parent of a Scala non-value reference type? This is because Scala can also run on other platforms such as. Net, so it uses the Anyref class, which corresponds to Java.lang.Object on the JVM, and different implementations for other platforms.

2 How to implement the native type of Scala

Scala uses the same native-type storage as Java, and because of its performance aspects and its operational considerations with Java, Scala's basic operations such as subtraction operations are the same as for Java, and when other method calls are required, the native type wrapper class of Java is used to represent it. If the int type corresponds to the Java.lang.Integer type, the conversion is transparent to our users.

In the second section of this lesson, we mention that the = = operation in Scala does not distinguish whether you are a native type or a reference type, such as

"abc"=="abc"Booleantrue

If it is in the Java language, it returns false. In Scala, for native types, this equals operation with the Java native type, and for reference types, it actually implements the = = Method with the Equals method, which avoids some of the problems stored in the program design. What if you want to determine if the two reference types are equal? The EQ, ne Two methods are provided in ANYREF to determine whether two references are equal, such as

scala> val x=newString("123"String123scala> val y=newString("123"String123BooleantrueBooleanfalseBooleantrue
3 Nothing, NULL type resolution

As you can see in the preceding class hierarchy diagram, the null type is a subtype of all anyref types, that is, it is at the bottom of the Anyref class and corresponds to a null reference in Java. Nothing is a subclass of all classes in the Scala class, which is at the very bottom of the Scala class.
It must be noted that the null type is at the bottom of the Anyref class, and it cannot be a subclass of a value type, for example:

scala> val x:Int=Null<console>:7errornotNull       val x:Int=Null                 ^

Nothing this class is generally used to instruct the program to return abnormal results, and using nothing as the return value can increase the flexibility of the program. For example:

def error(msg:String):Nothing={    throw new RuntimeException(msg)  }def divide(x: Int, y: Int): Int =if0) x / yelse error("can‘t divide by zero")
4 Traits Introduction

Scala, like the Java language, employs a strong restriction strategy that avoids multiple inheritance problems. In the Java language, only one superclass is allowed, and the class can implement multiple interfaces, but the Java interface has its own limitations: The interface can only include abstract methods, cannot contain fields, concrete methods. The Scala language solves this problem with trait, and in Scala's trait, it can include not only abstract methods but also fields and concrete methods. An example of trait is as follows:

//trait定义演示trait DAO{  //定义一个抽象方法,注意不需要加abstract  //加了abstract反而会报错  def delete(id:String):Boolean  def add(o:Any):Boolean  def update(o:Any):Int  def query(id:String):List[Any]}

Result of the resulting bytecode file being deserialized:

d:\scalaworkspace\scalachapter10\bin\cn\scala\xtwy>javap- Private  dao.classcompiled from  "Dao.scala"  Public  interface  cn.scala.xtwy.DAO {public  abstract  boolean delete  ( java.lang.String); public  abstract  boolean add  (Java.lang.Object); public  abstract  int  update  (Java.lang.Object); public  abstract  scala.collection.immutable.list<java.lang.object> query  (java.lang.String);} 

The following code demonstrates the use of the trait

trait MysqlDAO{  def add(o:Any):Boolean  def update(o:Any):Int  def query(id:String):List[Any]}class DaoImpl extends MysqlDAO{  def add(o:Any):Boolean=true  def1   def query(id:String):List[Any]=List(1,2,3)}

If there are multiple trait:

 trait Mysqldao{  varrecodemount:long=15000000000000LdefAdd (o:any): BooleandefUpdate (O:any): IntdefQuery (id:string): List[any]} class daoimpl extends Mysqldao  with cloneable{   defAdd (o:any): boolean=true  defUpdate (O:any): int=1  defQuery (id:string): List[any]=list (1,2,3)}
5 traits several different ways to use

1 as a trait used by the Java interface, such as

//trait定义演示trait DAO{  //定义一个抽象方法,注意不需要加abstract  //加了abstract反而会报错  def delete(id:String):Boolean  def add(o:Any):Boolean  def update(o:Any):Int  def query(id:String):List[Any]}

2 trait with a specific implementation

trait DAO{  //delete方法有具体实现  def delete(id:String):Boolean={    println("delete implementation")    true  }  def add(o:Any):Boolean  def update(o:Any):Int  def query(id:String):List[Any]}

The attributes defined here will generate two bytecode files:

Directory of D:\ScalaWorkspace\ScalaChapter10\bin\cn\scala\xtwy -/ -/ -   A: -<DIR>. -/ -/ -   A: -<DIR>.. -/ -/ -   A: -               575Dao$class.class -/ -/ -   A: -               898Dao.class2A file1,473Bytes2List of175,333,232,640Free bytes D:\scalaworkspace\scalachapter10\bin\cn\scala\xtwy>javap-Privatedao$class.classCompiled from"Dao.scala" Public Abstract classcn.scala.xtwy.dao$class{ Public StaticBooleanDelete(Cn.scala.xtwy.DAO, java.lang.String); Public Static void$init $ (Cn.scala.xtwy.DAO);} D:\SCALAWORKSPACE\SCALACHAPTER10\BIN\CN\SCALA\XTWY&GT;JAVAP-PrivateDao.classcompiled from"Dao.scala" Public Abstract classcn.scala.xtwy.dao$class{ Public StaticBooleanDelete(Cn.scala.xtwy.DAO, java.lang.String); Public Static void$init $ (Cn.scala.xtwy.DAO);}

As can be seen from the bytecode file, trait with a concrete implementation is implemented by an abstract class in Java.

3 Trait with abstract fields

trait DAO{  var recodeMount:Long  def delete(id:String):Boolean={    println("delete implementation")    true  }  def add(o:Any):Boolean  def update(o:Any):Int  def query(id:String):List[Any]}

4 Trait of specific fields

trait DAO{  var recodeMount:Long=15000000000000L  def delete(id:String):Boolean={    println("delete implementation")    true  }  def add(o:Any):Boolean  def update(o:Any):Int  def query(id:String):List[Any]}

Add a public number to find out more about the latest spark and Scala technical information

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Getting started with Scala-the tenth section of Scala class hierarchy, traits preliminary

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.