? :+letImplementation of theif-else?

While surfing the web this week, I came across this discussion: “How to write an elegant statement that combines Elvis and return and adds logic before return?” If else with the let syntax?: operator

account? .let { it.hello() it.name ="Hello"
} ?: run {
     logger.error("account is null")}Copy the code

There is a pit hidden here

At first glance, this may seem novel and creative, but in fact, let’s say that the grammar is followed by? : This approach is problematic.

Public inline fun

t. et(block: (T) -> R): R
,>

Together with the implementation, you can see that the let returns the return value of the block after it completes execution.

In Kotlin, unlike Java, each line of code is an expression, meaning that each line of code has a return value after execution.

Consider the following example:

// Example 1: nullable variable is null
val nullVal: Any? = nullnullVal? .let { println("[nullVal] not null code block")
    null
} ?: run {
    println("[nullVal] null code block")}// Example 2: nullable variables are non-null
valnotnull: Any? = Any() notnull? .let { println("[notnull] not null code block")
    null
} ?: run {
    println("[notnull] null code block")}Copy the code

You get the following output:

[nullVal] null code block

[notnull] not null code block
[notnull] null code block
Copy the code

The output of example 2 is clearly not expected.

In the example at the beginning of this article, since it. Name = “Hello” returns Unit, which is a non-empty value, it can be expected to be equivalent to if-else, but it actually leaves a hidden pit.

When writing code, you’re definitely not going to write code as silly as the example I gave above. Consider the following variations:

fun test_let(a) {
    val nullable: Any? = nullnullable? .let { println("[nullable] not null code block")
        maybeReturnNull(0)}? : run { println("[nullable] null code block")}valnotnull: Any? = Any() notnull? .let { println("[notnull] not null code block")
        maybeReturnNull(0)}? : run { println("[notnull] null code block")}}private fun maybeReturnNull(count: Int): Any? = if (count % 2= =0) null else Any()
Copy the code

Once you hit a pit like this, it’s going to take a lot of digging QAQ

After dropping such pits, you will find the simple if (XXX! = null) is actually the cutest way to write.

Tips

Here’s a tip:

The IDEA editor provides a template for quick nullation by typing.nn after the variable.

You get the following code.

PS: nn is short for notnull, type. Notnull also works.