美文网首页
kotlin null判断

kotlin null判断

作者: zghbhdxw | 来源:发表于2020-12-31 15:29 被阅读0次
  • 使用对象前判断空

// java 使用对象前判断空
public static void toUpperCase(String str) {
    if (str != null) {
        str.toUpperCase()
    }
}

// kotlin 使用对象前判断空
fun toUpperCase(str:String) {
    str?.toUpperCase()
}
  • 对象为null后处理
// java 对象为null后处理
public static int size(String str) {
    if (str != null)  {
        return str.length;
    } else {
        return -1;
    }
}

// kotlin 对象为null后处理
fun size(str: String): Int {
    return str?.length ?: -1
}

测试

 // 测试:kotlin 使用对象前判断空
    println("使用对象前判断空")
    println(toUpperCase(null))
    println(toUpperCase("aa"))

    // 测试:kotlin 对象为null后处理
    println("对象为null后处理")
    println(size(null))
    println(size("aa"))

测试结果

使用对象前判断空
null
AA
对象为null后处理
-1
2

相关文章

网友评论

      本文标题:kotlin null判断

      本文链接:https://www.haomeiwen.com/subject/autroktx.html