https://kotlinlang.org logo
Title
s

Sam

02/12/2022, 10:47 PM
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
@Composable
fun Greeting(name: String?) {
    name?.let { Text(text = "Hello $name!") } ?: Text(text = "Hello!")
}
🤔 1
r

Rick Regan

02/13/2022, 1:51 AM
a

Alexander Maryanovsky

02/13/2022, 5:41 AM
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

Chrimaeon

02/13/2022, 11:46 AM
It’s still a valid expression , @Alexander Maryanovsky although a if/else would be more readable in this case
a

Alexander Maryanovsky

02/13/2022, 12:06 PM
It is, but it’s not clear whether the behavior a bug. What’s the result of the expression
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

Chrimaeon

02/13/2022, 12:11 PM
yes, because the elvis operator on the
name
and not the result of
let
a

Alexander Maryanovsky

02/13/2022, 12:11 PM
Yeah, looks like the compose compiler is inserting some additional code there which causes the result to be
Unit
c

Chrimaeon

02/13/2022, 12:12 PM
Ah, that’s what you mean. Okay!
a

Alexander Maryanovsky

02/13/2022, 12:30 PM
But I’m seeing the same behavior with Compose 1.0.1 and Kotlin 1.5.31
m

Michael Paus

02/13/2022, 1:40 PM
The observed behaviour may be a bug but would this 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

Sam

02/13/2022, 2:21 PM
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

Alexander Maryanovsky

02/13/2022, 2:24 PM
@Sam It doesn’t matter what additional logic is inside those blocks. Just replace them with an
if … else …
s

Sam

02/13/2022, 2:25 PM
Yeah using as a workaround for now, but seems to be regression for sure
a

Alexander Maryanovsky

02/13/2022, 2:25 PM
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

Sam

02/13/2022, 2:25 PM
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