[kotlin] null pointer check in kotlin

Posted by kitegirl on Sat, 15 Jan 2022 00:31:42 +0100

kotlin learning - null pointer check

1.Java

In java code, null pointer errors are often reported, methods pass parameters, operate on data, or call collections. The general operation is to add a null judgment process

2.kotlin nullable type system

**In kotlin, all parameters and variables cannot be null by default, * * if NULL is passed, there will be a null value prompt, that is, kotlin will advance the null pointer exception to the compilation time. If there is a null pointer exception in the program, an error will be reported directly during compilation

Nullable type system is to add a?

For example: Int? An integer Int that represents nullable cannot be empty

fun main() {//Pseudo code
    
        doStudy(null)
        
}
fun doStudy(study : Study?){
    study.readBooks()
    study.doHomework()
}

What's added to Study here?, Therefore, it is allowed to pass null values, but null pointer exceptions may be caused when calling methods, so kotlin will prompt an error, and we only need to add a null judgment processing, because kotlin is not allowed to compile in this case

fun main() {
    
        doStudy(null)
        
}
fun doStudy(study : Study?){
    if(study ! =null){
    study.readBooks()
    study.doHomework()
    }
    
}

3. Auxiliary tools for air judgment

1. ?.

?. This operator is easy to understand, that is, when the object is not empty, the corresponding method is called normally, and when the object is empty, nothing is done

For example:

if(a ! =null){
   
       a.dosth
    }

You can change it to

 a?.dosth

Simplify previous code

fun doStudy(study : Study?){
    
    study?.readBooks()
    study?.doHomework()
   
    
}

2. ?:

The left and right sides of this operator receive an expression. If the result of the expression on the left is not empty, the result of the expression on the left will be returned. Otherwise, the result of the expression on the right will be returned

For example:

 val c =if (a!=null){
     a
 }else{
     b
 }

After simplification

val c =a ?: b

Combined with

For example:

fun getTextLenth(text:String?):Int{
    if(text !=null){
        return test.length
    }
    return 0
}

After simplification

fun getTextLenth(text:String?)=text?.length ?:0

If it is blank, 0 will be returned

3. !!

[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3ijgy9ib-1627106636565)( https://bytedance.feishu.cn/space/api/box/stream/download/asynccode/?code=MDU4ZGU1OGJjZjI1ZTU3YTcyZWQyOTlhZjFhZmFhOTVfMGpXRjE4amRJRnpXdEdGTm02NUp2em9YTW9IT2ZNaFZfVG9rZW46Ym94Y25XOVJKRHNHZVY3bm5Cd1NkdWM0QTdlXzE2MjcxMDY2MDk6MTYyNzExMDIwOV9WNA )]

We can make this change

val upperCase = content!!.toUpperCase()

Here, the printUpperCase function does not know that the content variable has been checked for non emptiness. When calling toUpperCase() method, it also considers that there is a risk of null pointers, so it cannot be compiled

So we can use the non empty assertion tool to add!!

This is a risky way to write

4.let

let is a function that provides a programming interface to a functional API and passes the original call object as a parameter to a Lambda expression

For example:

 fun main(){
    obj.let{obj2 ->
        //Write business logic code
    }
}

Obj is actually obj2. This is to prevent duplicate names

Go back to the doStudy function between

That's it

fun doStudy(study : Study?){
    
    study?.readBooks()
    study?.doHomework()
   
    
}

We could have done it by making an if judgment, but here we need to use, Therefore, the corresponding is to perform two empty judgment operations

So we can combine let and To optimize the code

fun doStudy(study : Study?){
    
    study?.let{stu ->
        stu.readBooks()
        stu.doHomework()
    }

}

Here it is Operator means that nothing is done when the object is empty. If the object is not empty, the let function will call, and the let function will pass the province of the study object as a parameter to the Lambda expression. At this time, the study object must not be empty.

With the Lambda feature, when there is only one parameter in the parameter list of Lambda expression, you can directly use the it keyword instead of declaring the parameter name

fun doStudy(study : Study?){
    
    study?.let{
        it.readBooks()
        it.doHomework()
    }
   
}

Finally, let function can handle the problem of null judgment of global variables, while if judgment statement can't.

var study : Study?=null
fun doStudy(){
    
    if(study != null){
        study.readBooks()
        study.doHomework()
    }
   
}

The reason why the error is reported here is that the value of the global variable may be modified by other threads at any time. Even if the null judgment processing is done, it is still impossible to ensure that the study variable in the if statement has no null pointer risk

Topics: Android kotlin