var name: String = "yc"
//編譯錯誤
//name = null
複製代碼
var name: String? = "yc"
name = null
複製代碼
fun check(name: String?): Boolean {
//編譯器不容許不對 name 作 null 檢查就直接調用其屬性
return name.isNotEmpty()
}
複製代碼
fun check(name: String?): Boolean {
if (name != null) {
return name.isNotEmpty()
}
return false
}
複製代碼
fun check(name: String?) {
if (name != null) {
println(name.toUpperCase())
} else {
println(null)
}
}
fun check(name: String?) {
println(name?.toUpperCase())
}
複製代碼
fun check(name: String?) {
if (name != null) {
println(name)
} else {
println("yc")
}
}
fun check(name: String?) {
println(name ?: "yc")
}
複製代碼
fun check(any: Any?) {
val result = any as? String
println(result ?: println("is not String"))
}
複製代碼
fun main(args: Array<String>) {
var name: String? = "yc"
check(name) //7
name = null
check(name) //KotlinNullPointerException
}
fun check(name: String?) {
println(name!!.length)
}
複製代碼
fun main(args: Array<String>) {
var name: String? = "yc"
check(name) //yc
name = null
check(name) //什麼都不會輸出
}
fun check(name: String?) {
name?.let {
println(name)
}
}
複製代碼
val name: String? = null
println(name.isNullOrEmpty()) //true
複製代碼
@kotlin.internal.InlineOnly
public inline fun CharSequence?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies (this@isNullOrEmpty != null)
}
return this == null || this.length == 0
}
複製代碼
public void showToast(Activity activity) {
if (activity == null) {
return;
}
}
複製代碼
public void showToast(@NonNull Activity activity) {
......
}
複製代碼
private var goodsId: String? = null
private fun Main(){
getName(goodsId!!)
}
private fun getName(name : String){
Log.i("", "---$name")
}
複製代碼
private fun Main(){
getName(goodsId)
}
private fun getName(name : String?){
Log.i("", "---$name")
}
複製代碼
var time: Long? = 1000
private fun Main(){
time!!.toFloat()
time?.toInt()
}
複製代碼
/**
* 用戶登錄
*/
@POST("user/login")
fun userLogin(
@Query("username") userName: String?,
@Query("password") password: String?
): Observable<ResponseBean<LoginBean>>
複製代碼
param?.let {
doSomething(it)
}
複製代碼