- Scala Programming Projects
- Mikael Valot Nicolas Jorand
- 399字
- 2021-07-23 16:25:15
Scala class hierarchy
All Scala types extend a built-in type called Any. This type is the root of the hierarchy of all Scala types. It has two direct subtypes:
- AnyVal is the root class of all value types. These types are represented as primitive types in the JVM.
- AnyRef is the root class of all object types. It is an alias for the class java.lang.Object.
- A variable of type AnyVal directly contains the value, whereas a variable of type AnyRef contains the address of an object stored somewhere in memory.
The following diagram shows a partial view of this hierarchy:
When you define a new class, it indirectly extends AnyRef. This being an alias for java.lang.Object, your class inherits from all the default methods implemented in Object. Its most important methods are as follows:
- def toString: String returns a string representation of an object. This method is called whenever you print an object using println. The default implementation returns the class's name followed by the address of the object in memory.
- def equals(obj: Object): Boolean returns true if the object is equal to another object, and false otherwise. This method is called whenever you compare two objects using ==. The default implementation only compares the objects' references, and hence is equivalent to eq. Fortunately, most classes from the Java and Scala SDK override this method to provide a good comparison. For instance, the class java.lang.String overrides the equals method to compare the content of the strings, character by character. Therefore, when you compare two strings with ==, the result will be true if the strings are the same, even if they are stored in different places in memory.
- def hashCode: Int is called whenever you put an object in Set or if you use it as a key in Map. The default implementation is based on the address of the object. You can override this method if you want to have a better distribution of the data in Set or Map, which can improve the performance of these collections. However, if you do so, you must make sure that hashCode is consistent with equals: if two objects are equal, their hashCodes must also be equal.
It would be very tedious to have to override these methods for all your classes. Fortunately, Scala offers a special construct called case class that will automatically override these methods for us.
推薦閱讀
- Cisco OSPF命令與配置手冊
- 微商之道
- EDA技術與VHDL編程
- C++黑客編程揭秘與防范
- 計算機網(wǎng)絡與數(shù)據(jù)通信
- 物聯(lián)網(wǎng)概論(第2版)
- Spring Cloud微服務架構進階
- 局域網(wǎng)組建、管理與維護項目教程(Windows Server 2003)
- 正在爆發(fā)的互聯(lián)網(wǎng)革命
- 光纖通信系統(tǒng)與網(wǎng)絡(修訂版)
- 通信十年:擁抱互聯(lián)網(wǎng)
- 物聯(lián)網(wǎng)基礎及應用
- 精通SEO:100%網(wǎng)站流量提升密碼
- 深入理解計算機網(wǎng)絡
- 物聯(lián)網(wǎng)M2M開發(fā)技術:基于無線CPU-Q26XX