4.3 根类型Any

Kotlin 中所有类都有一个共同的超类 Any ,如果类声明时没有指定超类,则默认为 Any 。我们来看一段代码:

  1. >>> val any = Any()
  2. >>> any
  3. java.lang.Object@2e377400
  4. >>> any::class
  5. class kotlin.Any
  6. >>> any::class.java
  7. class java.lang.Object

也就是说,Any在运行时,其类型自动映射成java.lang.Object。我们知道,在Java中Object类是所有引用类型的父类。但是不包括基本类型:byte int long等,基本类型对应的包装类是引用类型,其父类是Object。而在Kotlin中,直接统一——所有类型都是引用类型,统一继承父类Any

Any是Java的等价Object类。但是跟Java不同的是,Kotlin中语言内部的类型和用户定义类型之间,并没有像Java那样划清界限。它们是同一类型层次结构的一部分。

Any 只有 equals() 、 hashCode() 和 toString() 三个方法。其源码是

  1. public open class Any {
  2. /**
  3. * Indicates whether some other object is "equal to" this one. Implementations must fulfil the following
  4. * requirements:
  5. *
  6. * * Reflexive: for any non-null reference value x, x.equals(x) should return true.
  7. * * Symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  8. * * Transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
  9. * * Consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  10. *
  11. * Note that the `==` operator in Kotlin code is translated into a call to [equals] when objects on both sides of the
  12. * operator are not null.
  13. */
  14. public open operator fun equals(other: Any?): Boolean
  15. /**
  16. * Returns a hash code value for the object. The general contract of hashCode is:
  17. *
  18. * * Whenever it is invoked on the same object more than once, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
  19. * * If two objects are equal according to the equals() method, then calling the hashCode method on each of the two objects must produce the same integer result.
  20. */
  21. public open fun hashCode(): Int
  22. /**
  23. * Returns a string representation of the object.
  24. */
  25. public open fun toString(): String
  26. }

4.3.1 对象相等性

从Any的源码注释中,我们可以看到,判断两个对象是否相等,需要满足以下条件:

  • 自反性:对于任何非空引用值x,x.equals(x) 应返回true。
  • 对称性:对于任何非空引用值x和y,x.equals(y) 应返回true当且仅当y.equals(x) 返回true。
  • 传递性:对于任何非空引用值x,y,z,如果x.equals(y) 返回true,y.equals(z) 返回true,那么x.equals(z) 应返回true
  • 一致性:对于任何非空引用值x和y,多次调用x.equals(y) 始终返回true或者始终返回false。

另外,在Kotlin中,操作符==会被编译器翻译成调用equals() 函数。