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()
  • 相关阅读:
    小伙子的毕业设计
    mongoDB
    Java面试题笔试题收集
    react-router4 介绍
    React 组件间通信 总结
    react ajax
    react应用(基于react脚手架)
    React 之 组件生命周期
    组件收集表单数据
    组件的组合使用
  • 原文地址:https://www.cnblogs.com/huyang011/p/14278086.html
Copyright © 2011-2022 走看看