Introduction
kotlin, the object can be divided into two types, and may be a non-null object is an empty object
Default is non-null object code detecting if a null is found not to impart an empty object, an error will be marked red.
The object may be empty, if you call a method, error code detection is also marked red
var s: String = "hello" //不可为空
s = null//标红报错
var s: String? = "hello"
s=null //代码检测通过
println(s.length)//标红报错
Call may be empty object property or method
The advantage is that, if we have an object must be not empty, then we can call its methods without a null pointer error.
But if we need to call an empty property of the object, how to do it?
Above we know that if a null object calls the method, the code error detection monogram red, so, kotlin in provides several ways for us to call a property or method can be empty object
1. Empty judgment conditions if (xx! = Null)
var s: String? = "hello"
if(s!=null){
println(s.length)
}
2. Use safety calls?.
Use ?.
, if the object is empty, you will get null, but the program will not stop
Support for chained calls when somewhere object is empty, null is returned
var s: String? = "hello"
println(s?.length) //s为空,则返回null,否则返回s.length
println(s?.length+1) //这里代码检测会报错
println(s?.length?.plus(1)) //修改之后的,通过代码检测
3. Elvis operator?:
val date = Expression 1:? 2 expression
If the expression 1 is null, the expression returns 2 content returned
val l: Int = if (b != null) b.length else -1
//相当于上面的代码
//如果b为空,则返回l=-1,b不为空,l=b.length
val l = b?.length ?: -1
4. !!
Object is empty, compile (no error code hints), but run time throws null pointer exception
var s: String = null
pritnln(s!!.length) //运行时候回报错