天天看點

【Kotlin】Kotlin筆記9-空指針檢查(可空類型系統,判空輔助工具)

Kotlin筆記9-空指針檢查-可空類型系統,判空輔助工具?,?:

5.1 空指針檢查

​Example:​

public void doStudy(Study study){
    study.readBooks();
    study.doHomework();//不安全
}      
public void doStudy1(Study study){
  if(study!=null){
      study.readBooks();
        study.doHomework();//安全
  }
}      
  • 可空類型系統

​kotlin:​

fun doStudy(study: Study) {
  study.readBooks()
  study.doHomeWork()//不安全
}      
參數類型 ?
不可為空 可為空
Int Int?
String String?

正确寫法

fun doStudy1(study: Study?) {
    if (study != null) {
        study.readBooks()
        study.doHomework()
    }
}      

​if處理不了全局變量判空,kotlin是以引進判空輔助工具​

  • 判空輔助工具
?.
if(a != null) {
  a.doSomething()
}      
a?.doSomething      

​Example:​

fun doStudy2(study: Study?) {
    study?.readBooks()
    study?.doHomework()//其實還可以優化,往下看
}      
?:
val c = if (a != null) {
  a
} else {
  b
}      

​優化:​

val c = a ?: b      
fun getTextLength(text:String?):Int{
    if(text!=null){
        return text.length
    }
    return 0
}      
fun getTextLength1(text: String?)=text?.length?:0