Kotlin中多空安全调用链式表达式的else块实现咨询
Great question! When you've got a long null-safe chain like one?.two?.three?.four?.let { }, it's totally common to want a clean way to handle the case where any step in that chain comes up null—and luckily, Kotlin gives you a couple of idiomatic ways to add that else block.
1. Use the Elvis Operator + run (Most Concise)
The go-to approach for this scenario is combining your null-safe chain with the Elvis operator (?:) and a run block for your else logic. Here's how it looks in action:
one?.two?.three?.four?.let { four -> // Your code when all steps are non-null—use 'four' here println("Got a non-null four: $four") } ?: run { // Your else block: triggers if ANY step in the chain was null println("Oops, something in the chain was null!") }
Why this works:
- The
?.letonly executes its block iffouris non-null. If any step before that returns null, the entire left side of the?:becomes null. - The
runfunction lets you execute multiple lines of code in the else block without needing extra variables—it acts like a mini code block with its own scope.
2. Explicit if-else (For Clarity/Reusability)
If you prefer more explicit control, or if you need to reuse the non-null value later in your code, breaking the chain into a variable and using a standard if-else is a solid choice:
val four = one?.two?.three?.four if (four != null) { // Handle non-null case (same as the let block) println("Got a non-null four: $four") } else { // Handle null case println("Something in the chain was null!") }
This is especially useful if you need to reference four multiple times after the check—no need to re-run the chain.
A Quick Caveat
If your let block might return null on its own (not just because the chain failed), the Elvis operator will trigger the else block in that case too. If that's not what you want, stick with the explicit if-else approach to avoid unintended behavior.
Either way, both patterns are widely used in Kotlin codebases—pick whichever fits your readability needs and use case!
内容的提问来源于stack exchange,提问作者lulumeya

