Preface:

Recently, while learning Kotlin, I was refactoring the project code to kotlinization. During the refactoring process, I found some minor problems. There was a little friction when I tried kotlin let nesting if else. Let’s find out

The body of the

1. Take a look at some sample code:

SetBg returns a string. We should complete the else branch if we write it correctly
2. Another example of code:

Transpose the red box code in example 1, the error is not reported, why?
3. Here’s another example

An example of completing the else branch, where neither the code location of example 1 nor example 2 is reported as an error
4. Cause analysis:
If a==1, setBg() is a string, else if a== 2 returns void
Because there is no else branch and the above two return types are inconsistent, the compiler cannot deduce the final type
Example 2 analysis: If a ==1 branch returns void, else if(a == 2) branch returns void, the two types are the same, because there is no else branch, at least the existing branch returns the same type
Example 3 Analysis: All branches have return values, and the return value type can be fixed
5. To summarize
For the return value of let, if there are nested if branches and more branches, if there are no else branches, you need to ensure that all if branches return the same type

\