Colton Idle
01/03/2024, 3:33 PMif (foo.barr != null){
name = foo.bar!!
}
Why do I need the double bang operator if I just checked if the value was != null?Javier
01/03/2024, 3:35 PMval
or use let
ephemient
01/03/2024, 3:40 PMclass Foo {
var bar: Any?
}
that is updated in between your check and your assignment, or a custom getter
class Foo {
val bar: Any?
get() = field.also { field = null }
that changes nullability after read. if it's in a different compilation unit, Kotlin must assume the implementation may changeCLOVIS
01/03/2024, 3:45 PMval bar = foo.bar
if (bar != null)
name = bar // no problem
because you're storing it in a read-only local variable, Kotlin now knows that it's not possible for it to become nullable between the condition and the assignment, so it's safe.Pablichjenkov
01/03/2024, 3:58 PM!!
at all. Whenever you see it in code, a better approach is available 100% guaranteedJohann Pardanaud
01/03/2024, 4:00 PMfoo.bar?.let { name = it }
Pablichjenkov
01/03/2024, 5:30 PMfoo.bar?.also { dosomething(it) } ?: run {
println("It was null")
}
Expression if/else
val bar2 = foo.bar?.let { dosomethingAndReturnAValue(it) } ?: "DefaultValue"
Expression if/else with action
val bar2 = foo.bar?.let { dosomethingAndReturnAValue(it) } ?: run {
println("It was null")
"DefaultValue"
}
If you have default values:
val bar = foo.bar ?: "default"
Early return
val bar = foo.bar ?: return
Early return with result
val bar = foo.bar ?: return Result.Error("should not be null")
Early return with result and action:
val bar = foo.bar ?: run {
dosomethingWhenNull()
reportToNonFatalErrorFirebase()
return Result.Error("should not be null")
}
ephemient
01/03/2024, 8:14 PMwhen (val bar = foo.bar) {
null -> {
// ...
}
else -> {
// bar is smart-cast to non-null
}
}
is also possiblePablichjenkov
01/03/2024, 9:05 PMColton Idle
01/04/2024, 7:14 PMlet
. I feel like it just makes my head hurt. but maybe thats a good candidate here.Colton Idle
01/04/2024, 7:15 PMephemient
01/04/2024, 7:18 PMval
changing without any threading involvedephemient
01/04/2024, 7:21 PMval
without a custom getter in the same compilation unit, then Kotlin should allow the smart cast. otherwise it can'tColton Idle
01/04/2024, 7:22 PMephemient
01/04/2024, 7:24 PMephemient
01/04/2024, 7:27 PMval
in the version of the dependency you're compiling with, it's possible that your compiled code will get assembled together with a newer version of the dependency in the future in which it is changed to a var
, a binary compatible changeColton Idle
01/04/2024, 7:41 PM