網(wǎng)站首頁 編程語言 正文
1.在java中由于null引起的空指針異常,是一個(gè)運(yùn)行時(shí)異常。
在kotlin中為了避免這樣的問題,會(huì)在編譯期提示出來,而不是在運(yùn)行期才報(bào)錯(cuò)。
1)比如我們把null賦值給一個(gè)已經(jīng)被賦值的變量或者定義一個(gè)返回null的函數(shù),編譯器就會(huì)報(bào)錯(cuò)提示:Null can not be a value of a non-null type String
var hello = "hello world"
hello = null
fun getString(): String{
return null
}
2)如何把null賦值給一個(gè)變量,或者函數(shù),帶上一個(gè)?這樣編譯器就不會(huì)報(bào)錯(cuò)了。
var hello: String? = "hello world"
hello = null
fun getString(): String? {
return null
}
2.安全調(diào)用操作符:問號?
為了避免空指針,kotlin不讓我們給非空變量賦值null,但null在Kotlin中依存在,這種情況下,我們可以使用安全操作符 ?來避免發(fā)生空指針異常。
當(dāng)編譯器遇到安全調(diào)用操作符時(shí),會(huì)去檢查,如果是null,就會(huì)跳過函數(shù)的執(zhí)行,而不會(huì)拋出異常。
比如下面這幾行代碼,在java中必然會(huì)拋出異常,但是在kotlin中會(huì)跳過count()函數(shù)執(zhí)行,并返回null,不會(huì)拋出異常。
fun main() {
val str = getString()
val count = str?.count()
println(count)
}
fun getString(): String? {
return null
}
3.非空斷言操作符:!!雙感嘆號
!!又稱為感嘆號操作符,當(dāng)變量為null時(shí),會(huì)拋出空指針異常,NullPointerException
fun main() {
val str = getString()
val count = str!!.count()
println(count)
}
fun getString(): String? {
return null
}
4.在Kotlin中也可以用if來判斷null的情況
fun main() {
val str = getString()
if (str == null) {
println("null")
} else {
val count = str?.count()
println(count)
}
}
fun getString(): String? {
return null
}
5.空合并操作符?:
?: 如何符號左邊的值為null,則使用右邊的值。
下面這行代碼打印的結(jié)果就是 hello
fun main() {
val str = getString() ?: "hello"
println(str)
}
fun getString(): String? {
return null
}
6.Kotlin中捕獲異常 try catch
try {
val str = getString()
val count = str!!.count()
println(count)
} catch (e: Exception) {
e.printStackTrace()
}
原文鏈接:https://blog.csdn.net/niuyongzhi/article/details/126515015
相關(guān)推薦
- 2022-03-30 .Net?Core以windows服務(wù)方式部署_C#教程
- 2023-01-28 GoLang分布式鎖與snowflake雪花算法_Golang
- 2022-11-26 React?useReducer終極使用教程_React
- 2022-06-16 Golang協(xié)程池gopool設(shè)計(jì)與實(shí)現(xiàn)_Golang
- 2022-12-16 python靜態(tài)web服務(wù)器實(shí)現(xiàn)方法及代碼詳解_python
- 2022-05-26 C++的深淺拷貝和寫時(shí)拷貝你了解嗎_C 語言
- 2022-04-08 從頭學(xué)習(xí)C語言之二維數(shù)組_C 語言
- 2022-04-12 C++中的異常實(shí)例詳解_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支