The below code will print `B` ```null?.let { p...
# compose
t
The below code will print
B
Copy code
null?.let {
    println("A")
} ?: println("B")
but the below code doesn’t render
B
Copy code
null?.let {
    Text(text = "A")
} ?: Text(text = "B")
Why? 🤔
f
Maybe related to this?
👀 1
👌 1
a
but it’s also an anti-pattern, as I mentioned in that same thread
t
@Alexander Maryanovsky Can’t say “an anti-pattern”. Should belong to “personal preference” IMO. The above given sample is a very minimized version to reproduce the bug. When we have deep chaining and want a default behaviour when it’s null, this’ll come handy.
@Filip Wiesner Yes. It’s a bug.
p
I'd strongly vote for anti pattern as well. Just relying on the position of the unit returning expression is error prone.
m
have you tried using a run { } block around the null condition: null?.let { Text(text = “A”) } ?: run { Text(text = “B”) }
a
@theapache64 It’s an antipattern because if the value of the last expression inside the
let
happens to be
null
, you will have the part after the
?:
evaluated as well.
t
@mattinger Yes. It didn’t work. @Paul Woitaschek Sorry, I’d like to understand why you consider this is an anti-pattern. Let me explain my point.
Copy code
class User(val job: Job?)
class Job(val title: String?)

val user: User? = User(job = null)

// Option #1
user?.job?.title?.let { Text("Job title is $it") } ?: Text("No job title found")

// Option #2
val jobTitle = user?.job?.title
if (jobTitle == null) {
    Text("Job title is $jobTitle")
} else {
    Text("No job title found")
}
Here, I agree #2 gives a little more readability, but #2 helps us to avoid declare a local variable. What problem do you see with #1 ? 🤔
a
See above
t
Ohhkay. Now I got it. Agreed. I didn’t think of that. Thanks guys.
a
Feel free to star the issue I linked above; maybe Google will fix it faster.
t
Sure 👍