2.10 类型层次 Any、Unit、Nothing

欢迎访问我的CSDN

根类型Any

Kotlin中所有的类都有一个共同的基类Any,如果类没有申明继承其他类的话,默认继承的就是Any。其实Kotlin中的Any就是对应Java中的java.lang.Object类型。
Any的源码如下:

public open class Any {
    /**
     * Indicates whether some other object is "equal to" this one. Implementations must fulfil the following
     * requirements:
     *
     * * Reflexive: for any non-null value `x`, `x.equals(x)` should return true.
     * * Symmetric: for any non-null values `x` and `y`, `x.equals(y)` should return true if and only if `y.equals(x)` returns true.
     * * Transitive:  for any non-null values `x`, `y`, and `z`, if `x.equals(y)` returns true and `y.equals(z)` returns true, then `x.equals(z)` should return true.
     * * Consistent:  for any non-null 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.
     * * Never equal to null: for any non-null value `x`, `x.equals(null)` should return false.
     *
     * Read more about [equality](https://kotlinlang.org/docs/reference/equality.html) in Kotlin.
     */
    public open operator fun equals(other: Any?): Boolean
 
    /**
     * Returns a hash code value for the object.  The general contract of `hashCode` is:
     *
     * * 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.
     * * 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.
     */
    public open fun hashCode(): Int
 
    /**
     * Returns a string representation of the object.
     */
    public open fun toString(): String
}

根据源码,Any类型定义toString()、hashCode()和equals()方法。这三个方法跟Java中的意思是一样的,唯一不同的是,Any的equals在Kotlin中进行了操作符重载,所以大家可以使用==来进行值相等的比较。

Unit类型:

函数没有返回值的时候,我们用Unit来表示,大多数时候我们不需要显示地返回Unit,编译器会推断它。比如:

fun sumInt(first: Int, second: Int): Unit {
    println(first + second)
}

Uinit可以省略:

fun sumInt(first: Int, second: Int) {
    println(first + second)
}

下面我们来验证下两种写法的返回类型是否是Unit类型。

fun main(args: Array) {
    println(sumInt(1, 2))
    println(sumInt1(1, 5))
}
 
fun sumInt(first: Int, second: Int): Unit {
    println(first + second)
}
 
fun sumInt1(first: Int, second: Int) {
    println(first + second)
}

结果:

3
kotlin.Unit
6
kotlin.Unit

返回类型都是kotlin.Unit类型。因此得出结论两种写法是等价的。

Nothing类型:

在Kotlin类型层次结构的最底层就是类型Nothing,正如它的名字Nothing所暗示的,Nothing是没有实例的类型。

注意:Unit类型表达式计算结果的返回类型是Unit。Nothing类型的表达式计算结果是永远不会返回的(跟Java中的void相同)。Nothing它唯一允许的值是null,被用作任何可空类型的空引用。

你可能感兴趣的:(2.10 类型层次 Any、Unit、Nothing)