Kotlin中Any, Unit和Nothing的区别

Any

Any 类有3个方法

public open class Any {
   public open operator fun equals(other: Any?): Boolean
   public open fun hashCode(): Int
   public open fun toString(): String
}

这个类就是Kotlin的基类, 任何类的顶级父类都是Any。  就相当于Java的Object那个类。

Unit

Unit类 是一个object类, 意味着它只有一个实例对象。

Unit is Any

Unit类也是一个Any类型的类,

Unit类完全等同于Java中的void类型。

当函数无返回值时,我们可以显式添加Unit作为函数的返回值

fun doSomething() {
    //do something here
}

fun doSomething() : Unit {
    //do something here
}

 

Nothing

public class Nothing private constructor()

Nothing代表一个从未使用过的值

常被作为一个每次只抛出异常的函数的返回值

fun iWillAlwaysThrowException() : Nothing =  throw Exception("Unnecessary Exception")

这个Nothing返回值不能省略

 

Nothing最好的例子 是TODO函数

@kotlin.internal.InlineOnly
public inline fun TODO(): Nothing = throw NotImplementedError()

 

posted @ 2021-01-14 16:54  huyang011  阅读(830)  评论(0编辑  收藏  举报