天天看点

【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