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))
}
}