官术网_书友最值得收藏!

Any

A little excerpt from Scala's official website about the root of all classes:

"Class Any is the root of the Scala class hierarchy. Every class in a Scala execution environment inherits directly or indirectly from this class. Starting with Scala 2.10 it is possible to directly extend Any using universal traits. A universal trait is a trait that extends Any, only has defs as members, and does no initialization."

Yes, Any is the super class of all the existing or defined classes in Scala. If you don't know what inheritance or super class is, here's a quick example for you. Let's say we defined a type Item for our newly opened store's order management application. Each Item has some parameters such as id. We further want to categorize our items and come up with several item categories, such as ElectronicItem and others. Now, ElectronicItem can be a subtype of Item, and Item will be called a super type of ElectronicItem, hence it doesn't have to declare those three parameters again, and can use them directly to assign values. Take a look:

import java.util.UUID

class Item {
val id: UUID = UUID.randomUUID()
}

class ElectronicItem(val name: String, val subCategory: String) extends Item {
val uuid: String = "Elec_" + id
}

object CartApp extends App {

def showItem(item: ElectronicItem) = println(s"Item id: ${item.id} uuid: ${item.uuid} name: ${item.name}")

showItem(new ElectronicItem("Xperia", "Mobiles"))
showItem(new ElectronicItem("IPhone", "Mobiles"))
}

The following is the result:

Item id: 16227ef3-2569-42b3-8c5e-b850474da9c4 uuid: Elec_16227ef3-2569-42b3-8c5e-b850474da9c4 name: Xperia

Item id: 1ea8b6af-9cf0-4f38-aefb-cd312619a9d3 uuid: Elec_1ea8b6af-9cf0-4f38-aefb-cd312619a9d3 name: IPhone

This example shows what we intended with inheritance. "The ElectronicItem function extends Item" that means "every ElectronicItem is an item." That's why we're able to refer to ID, UUID, and the name from an ElectronicItem instance. We've used the import statement to bring UUID type in scope of our compilation unit, so that when we use UUID, it should not give a compile-time error.

Now, as we discussed, every class is a subclass of Any. Hence, we have access to all non-private members of Any. Methods like != , ==, asInstanceOf, equals, isInstanceOf, toString, and hashCode are defined in Any class. These are in the form of:

final def  !=  (that: Any): Boolean 
final def == (that: Any): Boolean
def isInstanceOf[a]: Boolean
def equals(that: Any): Boolean
def ##: Int
def hashCode: Int
def toString: String

And yes! You can override these non-final methods, which means you can have your own definition of these.

主站蜘蛛池模板: 兴城市| 石泉县| 宣武区| 尉氏县| 固阳县| 祁连县| 遂川县| 九江市| 扎鲁特旗| 响水县| 正蓝旗| 嵩明县| 青浦区| 雷波县| 汶上县| 静宁县| 孝义市| 惠州市| 辽阳县| 昌宁县| 西乌| 梨树县| 缙云县| 江北区| 长葛市| 香港| 陕西省| 海阳市| 龙山县| 辰溪县| 秭归县| 威远县| 贡觉县| 丹阳市| 武平县| 垫江县| 若尔盖县| 鄂州市| 临海市| 阳谷县| 铁岭市|