kotlin ?. ?:

demo1 :

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 *
 *      let / run / also / apply
 */
class Test {

    private var user: User? = null

    /**
     *  ?.
     *  为null , 返回null
     *  不为null , 继续执行
     */
    @Test
    fun test1() {
        println("?.===== ${user?.getHeight()}")

        println("=========================================")
        user = User("xq", 18)

        println("?.===== ${user?.getHeight()}")

//        // ?. 等效于 下面代码
//        if (user != null) {
//            return user.getHeight()
//        } else {
//            return null
//        }
    }

    /**
     *  ?:
     *  为null ,返回后面默认值
     *  不为null , 直接返回
     */
    @Test
    fun test2() {
        println("?:===== ${user?.name ?: "qx"}")

        println("=========================================")
        user = User("xq", 18)

        println("?:===== ${user?.name ?: "qx"}")

//      //?: 等价于下面代码
//        if (user?.name != null) {
//            return user?.name
//        } else {
//            return "qx"
//        }
    }
}

class User(var name: String = "", var age: Int = 0) {
    fun getHeight(): String {
        return "180"
    }
}

demo2 :


```kotlin
object Test1 {
    @JvmStatic
    fun main(args: Array<String>) {
        val a1: String? = null
        val a2: Int? = null
        val a3 = "3"
        val a4 = 4
        println("a1======>" + (a1?.toString() ?: "默认666"))
        println("a2======>" + (a2?.toString() ?: "默认666"))
        println("a3======>" + (a3?.toString() ?: "默认666"))
        println("a4======>" + (a4?.toString() ?: "默认666"))

        //null cannot be cast to non-null type kotlin.String
//        println("a1 as String======>" + (a1 as String))
        //null cannot be cast to non-null type kotlin.String
//        println("a2 as String======>" + (a2 as String))
        //java.lang.Integer cannot be cast to java.lang.String
//        println("a3 as String======>" + (a3 as String))
        //java.lang.Integer cannot be cast to java.lang.String
//        println("a4 as String======>" + (a4 as String))
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值