zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    关于博客转移
    Leetcode 双周赛 42 题解
    Leetcode 220 周赛 题解
    Leetcode 双周赛 41 题解
    Leetcode 周赛 219 题解
    求解组成最大最小周长三角形
    友链
    维护日志
    投喂记录
    Scipy.optimization
  • 原文地址:https://www.cnblogs.com/huyang011/p/14278086.html
Copyright © 2011-2022 走看看