Hi folks, Compose 1.1.0 can’t seem to handle ?: wi...
# compose
s
Hi folks, Compose 1.1.0 can’t seem to handle ?: with null values, doesn’t generate text on null input. It works fine in 1.0.5 with Kotlin 1.5.31
Copy code
@Composable
fun Greeting(name: String?) {
    name?.let { Text(text = "Hello $name!") } ?: Text(text = "Hello!")
}
🤔 1
r
a
That's a weird way to use let and ?:
You realize the ?: is used on the value of the let expression? If the value of the last expression inside the let happens to be
null
the else part of the ?: will be executed.
c
It’s still a valid expression , @Alexander Maryanovsky although a if/else would be more readable in this case
a
It is, but it’s not clear whether the behavior a bug. What’s the result of the expression
Copy code
name?.let { Text(text = "Hello $name!") }
if
name
is
null
? On the face of it, it’s
null
, but actually it’s
Unit
. Not sure why, but there’s probably a good explanation.
Although there does seem to be something deeper here. If I replace
Text(…)
with
println(…)
it works as expected, and the result is
null
.
c
yes, because the elvis operator on the
name
and not the result of
let
a
Yeah, looks like the compose compiler is inserting some additional code there which causes the result to be
Unit
c
Ah, that’s what you mean. Okay!
a
But I’m seeing the same behavior with Compose 1.0.1 and Kotlin 1.5.31
m
The observed behaviour may be a bug but would this code
Copy code
@Composable
fun Greeting(name: String?) {
    Text(if (name != null) "Hello $name!" else "Hello!")
}
not be several times more readable and also less error prone (for the developer and the compiler)?
👍 1
s
This usage of ?: was just for minimum steps, the actual usage in app involves additional logic within those blocks.
@Alexander Maryanovsky >> But I’m seeing the same behavior with Compose 1.0.1 and Kotlin 1.5.31 Different behavior at my end with 1.0.5 and 1.5.21, ?: works just fine
a
@Sam It doesn’t matter what additional logic is inside those blocks. Just replace them with an
if … else …
s
Yeah using as a workaround for now, but seems to be regression for sure
a
Even if there was no compose bug here, you’re relying on the last statement in the
let
not returning
null
Which is probably a bad idea
s
Wonder if there are any other tricky usage around nullable types that might fail at runtime
Sure, point taken but really crazy how plugin can break basic stuff