Kotlin数据类型 Unit、Nothing与Nothing?、Any与Any?

Kotlin数据类型 Unit、Nothing与Nothing?、Any与Any?

本文链接:https://blog.csdn.net/ldxlz224/article/details/94403626
  • Unit类型
    Kotlin也是面向表达的语言。在Kotlin中所有控制流语句都是表达式(除了变量赋值,异常等)
    Kotlin中Unit类型实现了与java中void一样的功能。
public object Unit {// Unit类型是一个object对象类型
    override fun toString() = "kotlin.Unit" // toString函数返回值
}
  • 1
  • 2
  • 3

当一个函数没有返回值的时候,我们用Unit来表示这个特征,而不是null,大多数时候我们不需要显示地返回Unit,或者生命一个函数的返回值是Unit,编译器会推断它。

fun unitExample() {
        println("test,Unit")
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val helloUnit = unitExample()
        println(hellUnit)
        println(hellUnit is kotlin.Unit)
    }

输出结果
在这里插入图片描述
可以看出变量helloUnit的类型是kotlin.Unit类型。以下写法是等价的

 fun unitExample():kotlin.Unit {
        println("test,Unit")
    }
    fun unitExample(){
        println("test,Unit")
        return kotlin.Unit
    }
    fun unitExample(){
        println("test,Unit")
    }

跟其他类型一样,Kotlin.Unit的类型是Any。如果是一个可空的Unit?那么父类型是Any?。

  • Nothing与Nothing?
    在java中void不能是变量的类型,也不能作为值打印输出。但是在java中有个包装类Void是void的自动装箱类型。如果你想让一个方法的返回类型永远是null的话,可以把返回类型为这个大写的Void类型。
public Void testV() {//声明类型是Void
        System.out.println("am Void");
        return null;//返回值只能是null
    }

    public static void main(String[] args) {
        JavaTest test = new JavaTest();
        Void aVoid = test.testV();
        System.out.println(aVoid);
    }

打印结果如下
在这里插入图片描述
这个Void对应的类型是Nothing?,其唯一可被访问的返回值也是null,Kotlin中类型层次结构最底层就是Nothing
Nothing的类定义如下

//Nothing的构造函数是private的,外界无法创建Nothing对象
public class Nothing private constructor()

在这里插入图片描述
如果一个函数返回值是Nothing,那么这个函数永远不会有返回值。
但是我们可以使用Nothing来表达一个从来不存在的返回值。例如EmptyList中的get函数

object EmptyList : List<Nothing> {

        override fun get(index: Int): Nothing {
            throw IndexOutOfBoundsException()
        }
 }

因为get永远不会反回值,而是直接抛出了异常,这个时候可以用Nothing作为get函数的返回值。
再例如Kotlin标准库里面的exitProcess()函数

@kotlin.internal.InlineOnly
public inline fun exitProcess(status: Int): Nothing {
    System.exit(status)
    throw RuntimeException("System.exit returned normally, while it was supposed to halt JVM.")
}

Unit与Nothing之间的区别是,Unit类型表达式计算结果返回值是Unit;Nothing类型表达式计算结果永远是不会反回的,与java中void相同。
Nothing?可以只包含一个值 null 。
在这里插入图片描述
Nothing?唯一允许的值是null,可被用作任何可空类型的空引用。

  • Any?是可空类型的根。Any?是Any的超集,Any?是Kotlin类型层次的最顶端。
		println(1 is Any)
        println(1 is Any?)
        println(null is Any)
        println(1 is Any?)
        println(Any() is Any?)

输出如下

true
true
false
true
true

有关Kotlin编程电子书收藏(下载地址

原文地址:https://www.cnblogs.com/it-tsz/p/11620243.html