- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 139字
- 2021-06-24 19:15:24
The Nothing type
Nothing is the type that sits at the bottom of the entire Kotlin hierarchy. Nothing extends all Kotlin types, including Nothing?.
But, why do we need a Nothing and Nothing? types?
Nothing represents an expression that can't be executed (basically throwing exceptions):
val result: String = nullableCupcake?.eat() ?: throw RuntimeException() // equivalent to nullableCupcake!!.eat()
On one hand of the Elvis operator, we have a String. On the other hand, we have Nothing. Because the common type between String and Nothing is String (instead of Any), the value result is a String.
Nothing also has a special meaning for the compiler. Once a Nothing type is returned on an expression, the lines after that are marked as unreachable.
Nothing? is the type of a null value:
val x: Nothing? = null
val nullsList: List<Nothing?> = listOf(null)
推薦閱讀
- Instant Testing with CasperJS
- Advanced Machine Learning with Python
- Reporting with Visual Studio and Crystal Reports
- 從零開始:數字圖像處理的編程基礎與應用
- Learning Docker
- Linux C/C++服務器開發實踐
- Oracle數據庫從入門到運維實戰
- Node.js全程實例
- Keras深度學習實戰
- Visual Studio Code 權威指南
- Django Design Patterns and Best Practices
- 從零開始學Selenium自動化測試:基于Python:視頻教學版
- Secret Recipes of the Python Ninja
- Python硬件編程實戰
- Python數據科學實踐指南