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編程電子書收藏(下載地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM