美文网首页面试题Android笔记本
Kotlin判空的各种操作

Kotlin判空的各种操作

作者: 缺牙青蛙 | 来源:发表于2019-10-15 17:30 被阅读0次

    个人原创,转载请注明出处:https://www.jianshu.com/p/e7049cef9431

    If not null

    val files = File("Test").listFiles()
    println(files?.size)
    

    If not null or else

    val files = File("Test").listFiles()
    println(files?.size ?: "empty")
    

    If not null and true

    if (someObject?.status == true)  doThis()
    

    someObject?.takeIf{ it.status }?.apply{ doThis() }
    

    If not null and true or else

    if (someObject?.status == true)  {
        doThis()
    }else {
        doThat()
    }
    

    someObject?.takeIf{ it.status }?.apply{ doThis() } ?: apply{ doThat() }
    

    if not null 赋值

    val objA = ...
    val objB = ...
    objB.value = objA.value ?: objB.value
    

    if null 赋值

    val objA = ...
    val objB = ...
    objB.value = objB.value ?: objA.value
    

    if null 执行一个语句

    val values = ……
    val email = values["email"] ?: throw IllegalStateException("Email is missing!")
    

    参考

    https://www.kotlincn.net/docs/reference/idioms.html

    相关文章

      网友评论

        本文标题:Kotlin判空的各种操作

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