Scala Standard Library API(01) -- scala.Any

本文详细介绍了 Scala 中 Any 类的功能及用途,包括其作为 Scala 类层级的根类特性、类成员介绍,以及如何通过 universal traits 扩展 Any 类。此外,还深入探讨了 Any 类中的重要方法,如 equals 和 hashCode 的实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.scala-lang.org/api/current/index.html#scala.Any

个人学习笔记,本人初学编程语言,力争第一遍能了解scala基本库中的API的作用并发现不理解的问题,争取再深入学习时能够有针对性的进行研究和学习。水平有限难免会有理解错误。如有读者发现错误或者有问题可以留言指教。希望大家不吝赐教!文中会引用他人的博客的连接,如遇版权问题请联系我,立刻纠正。感谢前辈们的宝贵总结。

1. Any类的简述

Class Any is therootof 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.

The main use case for universal traits is to allow basic inheritance of methods for value classes. For example,

trait Printable extends Any {
  def print(): Unit = println(this)
}
class Wrapper(val underlying: Int) extends AnyVal with Printable

val w = new Wrapper(3)
w.print()

See the Value Classes and Universal Traits for more details on the interplay of universal traits and value classes.

Any类是scala中其它类的root(根),其它的类都直接或者间接的继承自Any类。从2.10版本开始,可以直接的使用universal traits来扩展(extends)Any类。一个universal traits仅仅含有使用def定义的成员(方法成员),没有value(值成员),没有初始化操作。def在scala中用来定义函数或者方法。

universal traits的主要用例就是用来继承value classes(我的理解就是从class里面继承value:也就是java中的成员变量)。


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2. 类成员

Abstract Value Members

  1. abstract defgetClass()Class[_]

    Returns the runtime class representation of the object.

    returns

    a class object corresponding to the runtime type of the receiver.

    Any类的抽象成员,返回值是这个class对象在运行时的相应的类的类型。

Concrete Value Members

Concrete Value Members

  1. final def!=(arg0: Any)Boolean

    Test two objects for inequality.

    returns

    true if !(this == that), false otherwise.


    比较两个对象是否相等,返回这和两个对象的class类型有关,例如:

    scala> val a = Array(1,2,3)
    a: Array[Int] = Array(1, 2, 3)
    
    scala> val b = Array(1,2,3)
    b: Array[Int] = Array(1, 2, 3)
    
    scala> a != b
    res19: Boolean = true
    
    scala> val a = 1
    a: Int = 1
    
    scala> val b = 1
    b: Int = 1
    
    scala> a != b
    res9: Boolean = false
    
    scala> val a = List(1,2,3)
    a: List[Int] = List(1, 2, 3)
    
    scala> val b = List(1,2,3)
    b: List[Int] = List(1, 2, 3)
    
    scala> a != b
    res18: Boolean = false


    具体的原因还待仔细研究。

  2. final def##()Int

    Equivalent to x.hashCode except for boxed numeric types and null. For numerics, it returns a hash value which is consistent with value equality: if two value type instances compare as true, then ## will produce the same hash value for each of them. For nullreturns a hashcode where null.hashCode throws a NullPointerException.

    returns

    a hash value consistent with ==

    除了boxed numberic类型和null之外,##()和java中的hashCode一样。对于数值来说,##()就是这个值等于数值的本身,如果两个值都是引用类型的==操作为真的话,那么##()将会生成同样的hash值。在scala中null.##()为0,而在Java中,null.hashCode则会抛出NullPointerException异常,如下:

    scala> val a = List(1,2,3)
    a: List[Int] = List(1, 2, 3)
    
    scala> val b = List(1,2,3)
    b: List[Int] = List(1, 2, 3)
    
    scala> a.##()
    res0: Int = 387518613
    
    scala> b.##()
    res1: Int = 387518613
    
    scala> a.##() == b.##()
    res2: Boolean = true
    
    scala> val c = List(1,2,3,4)
    c: List[Int] = List(1, 2, 3, 4)
    
    scala> a.##() == c.##()
    res3: Boolean = false
    
    scala> 1.##() == 1.##()
    res4: Boolean = true
    
    scala> "a".##()
    res5: Int = 97
    
    scala> "a".hashCode
    res6: Int = 97
    
    scala> 1.##
    res7: Int = 1
    
    scala> 1.hashCode
    res8: Int = 1
    
    scala> a.hashCode
    res9: Int = 387518613
    
    scala> b.hashCode
    res10: Int = 387518613
    

    参考url

    http://stackoverflow.com/questions/32887997/what-does-documentation-mean-by-boxed-numeric

    http://stackoverflow.com/questions/32054647/synthetic-function-in-scala/32054844#32054844


  3. final def==(arg0: Any)Boolean

    Test two objects for equality. The expression x == that is equivalent to if (x eq null) that eq null else x.equals(that).

    returns

    true if the receiver object is equivalent to the argument; false otherwise.

    与!=对应,判断两个值是不是相等,如果是相等的话就返回true,否则返回false,例如:

    <span style="font-weight: inherit;">scala> val a = Array(1,2,3)
    a: Array[Int] = Array(1, 2, 3)
    
    scala> val b = Array(1,2,3)
    b: Array[Int] = Array(1, 2, 3)
    
    scala> val c = List(1,2,3)
    c: List[Int] = List(1, 2, 3)
    
    scala> a==b
    res15: Boolean = false    </span><strong><span style="color:#ff0000;">这应该和scala的赋值机制有关,暂时还未了解和透彻,后面接着深入了解</span></strong><span style="font-weight: inherit;">
    
    
    scala> val d = a         
    d: Array[Int] = Array(1, 2, 3)
    
    scala> a==d
    res17: Boolean = true     <span style="font-weight: bold; font-size: 13.3333px; font-family: inherit; font-style: inherit;"><span style="color:#ff0000;">这应该和scala的赋值机制有关,暂时还未了解和透彻,后面接着深入了解</span></span>
    </span>


  4. final defasInstanceOf[T0]T0

    Cast the receiver object to be of type T0.

    Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression 1.asInstanceOf[String]will throw a ClassCastException at runtime, while the expression List(1).asInstanceOf[List[String]] will not. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested type.

    returns

    the receiver object.

    Exceptions thrown

    ClassCastException if the receiver object is not an instance of the erasure of type T0.

    一部分理解起来有点困难,先看了一下这篇文章 http://itang.iteye.com/blog/1128707

    这个方法的作用就是将原来的对象转换成T0对象,返回值是原来的对象。例如:

    scala> val a = List(1).asInstanceOf[List[String]]
    a: List[String] = List(1)
    
    scala> a
    res33: List[String] = List(1)
    


  5. defequals(arg0: Any)Boolean

    Compares the receiver object (this) with the argument object (that) for equivalence.

    Any implementation of this method should be an equivalence relation:

    • It is reflexive: for any instance x of type Anyx.equals(x) should return true.
    • It is symmetric: for any instances x and y of type Anyx.equals(y) should return true if and only if y.equals(x) returns true.
    • It is transitive: for any instances xy, and z of type Any if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z)should return true.

    If you override this method, you should verify that your implementation remains an equivalence relation. Additionally, when overriding this method it is usually necessary to override hashCode to ensure that objects which are "equal" (o1.equals(o2) returns true) hash to the same scala.Int. (o1.hashCode.equals(o2.hashCode)).

    returns

    true if the receiver object is equivalent to the argument; false otherwise.

    比较两个对象之间的相等性。任何实现这个方法的人都必须注意等效性关系:

    1. 自等性,任何的Any类型的x,x.equals(x)都为true;

    2. 对称性,任何Any类型的x和y,当且仅当y.equals(x)为true的时候,x.equals(y)才为true;

    3. 传递性,任何的x,y,z实例,如果x.equals(y)为true,y.equals(z)也为true,那么x.equals(z)为true。

    如果override这个方法的时候,必须满足上述的三个要求,而且,override这个方法的时候也要override下面的hashCode方法。

    例子:

    scala> val a = Set(1,2,3)
    a: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
    
    scala> val b = Set(1,2,3)
    b: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
    
    scala> a.equals(b)
    res34: Boolean = true
    
    scala> val c = b
    c: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
    
    scala> a.equals(c)
    res35: Boolean = true
    
    scala> 1.equals(2)
    res36: Boolean = false
    
    scala> 1.equals(1)
    res37: Boolean = true<span style="color:#ff0000;font-weight: bold;">
    </span>


  6. defhashCode()Int

    Calculate a hash code value for the object.

    The default hashing algorithm is platform dependent.

    Note that it is allowed for two objects to have identical hash codes (o1.hashCode.equals(o2.hashCode)) yet not be equal (o1.equals(o2) returns false). A degenerate implementation could always return 0. However, it is required that if two objects are equal (o1.equals(o2) returns true) that they have identical hash codes (o1.hashCode.equals(o2.hashCode)). Therefore, when overriding this method, be sure to verify that the behavior is consistent with the equals method.

    returns

    the hash code value for this object.

    为对象计算一个hash码,返回值为Int类型。

    默认的hash算法是独立于平台的。

    允许两个不相等的对象拥有相同的hash码。A degenerate implementation could always return 0(这句话没明白)。如果两个对象相等,那么一定返回相同的hash码。因此,override这个方法的时候,要验证equals方法的有效性。

    例子:

    scala> false.hashCode
    res47: Int = 1237
    
    scala> 1237.hashCode
    res48: Int = 1237
    
    scala> 1237.equals(false)
    res49: Boolean = false
    


  7. final defisInstanceOf[T0]Boolean

    Test whether the dynamic type of the receiver object is T0.

    Note that the result of the test is modulo Scala's erasure semantics. Therefore the expression 1.isInstanceOf[String] will returnfalse, while the expression List(1).isInstanceOf[List[String]] will return true. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the specified type.

    returns

    true if the receiver object is an instance of erasure of type T0false otherwise.

    测试某个对象是不是T0。类似于asInstanceOf[T0]

  8. deftoString()String

    Returns a string representation of the object.

    The default representation is platform dependent.

    returns

    a string representation of the object.

    将现有的对象转换成String类型,默认的表示与平台无关。









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值