https://kotlinlang.org logo
#compose
Title
# compose
t

theapache64

03/01/2022, 3:07 PM
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

Filip Wiesner

03/01/2022, 3:11 PM
Maybe related to this?
👀 1
👌 1
a

Alexander Maryanovsky

03/01/2022, 4:01 PM
but it’s also an anti-pattern, as I mentioned in that same thread
t

theapache64

03/01/2022, 4:45 PM
@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

Paul Woitaschek

03/01/2022, 6:18 PM
I'd strongly vote for anti pattern as well. Just relying on the position of the unit returning expression is error prone.
m

mattinger

03/01/2022, 6:22 PM
have you tried using a run { } block around the null condition: null?.let { Text(text = “A”) } ?: run { Text(text = “B”) }
a

Alexander Maryanovsky

03/01/2022, 6:49 PM
@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

theapache64

03/01/2022, 6:49 PM
@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

Alexander Maryanovsky

03/01/2022, 6:49 PM
See above
t

theapache64

03/01/2022, 6:50 PM
Ohhkay. Now I got it. Agreed. I didn’t think of that. Thanks guys.
a

Alexander Maryanovsky

03/01/2022, 6:53 PM
Feel free to star the issue I linked above; maybe Google will fix it faster.
t

theapache64

03/01/2022, 6:56 PM
Sure 👍
6 Views