kotlin中的Any,Unit,Nothing,Void的区别

2022-09-25  本文已影响0人  ModestStorm

Any

/**
 * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass:Any类是kotlin中的所有父类,相当于java中的Object
 */
public open class Any {
 
    public open operator fun equals(other: Any?): Boolean

    public open fun hashCode(): Int

    public open fun toString(): String
}

Any类声明了equals/hashcode/toString方法,Any类相当于java中的Object,是所有类的父类。

Unit

Unit类是一个object类,意味着它在进程中只有一个实例对象

public object Unit {
    override fun toString() = "kotlin.Unit"
}

Unit类也是Any类的子类,常作为函数的默认返回值,相当于java中的void。

fun doSomething() {
    //do something here
}

// Unit返回值也可以去掉
fun doSomething() : Unit {
    //do something here
}

Nothing

Nothing是一个具有私有的构造函数类,外部不可以创建

public class Nothing private constructor()

Nothing 常被作为抛出异常函数的返回值,而且Nothing关键字不可以省略

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

另外Nothing也常用在todo的方法声明中

public inline fun TODO(): Nothing = throw NotImplementedError()

Void

Void类是私有构造函数的类

public final class Void {
    @SuppressWarnings("unchecked")
    public static final Class<Void> TYPE = (Class<Void>) Class.getPrimitiveClass("void");
    /*
     * The Void class cannot be instantiated.
     */
    private Void() {}
}

Void常被作为强制返回null的返回值,正常情况下使用Unit即可

 public open fun play(path:String): Void? {
        return null
    }
// 二者是等价的,Unit关键字相当于java中的void
public open fun play(path:String): Unit? {
        return null
    }

//有明确返回值return时,需要指定方法返回值类型
 public open fun play(path:String): Int {
        return 2
    }

上一篇 下一篇

猜你喜欢

热点阅读