StavFX
11/19/2020, 5:51 PMfoo
is not being smart casted to non-null even tho it cannot be null in that else block.
Shouldn’t the compiler be smart enough to infer this?
class Foo(val str: String? = "")
val foo: Foo? = null
if (foo?.str.isNullOrBlank()) {
//...
} else {
println(foo.str) // doesn't compile. foo is not smart-casted to a non-null type
}
Btw if the condition was foo?.str == null
, this would compile. so it’s not impossible to “backtrack” from str
to foo
in this caseJoel
11/19/2020, 7:08 PMfoo?.str
, not foo
. This works:
class Foo(val str: String? = "")
val foo: Foo? = null
val str = foo?.str
if (str.isNullOrBlank()) {
//...
} else {
println(str)
}
Does the difference make sense?StavFX
11/19/2020, 7:24 PMfoo?.str != null
leads to smartcasting of foo
and not just str
, so should the other casesJoel
11/19/2020, 7:27 PMfoo?.str?.takeIf { it.isNotBlank() }?.let { println(it) }
StavFX
11/19/2020, 7:30 PMval result = if (foo?.str.isNullOrBlank()) {
""
} else {
"some format of $it"
}
And sure, I could be all fancy and do it like this
val result = foo?.str
?.takeIf { it.isNotBlank() }
?.let { "some format $it" }
?: ""
But I think that’s less readable than if it's valid, format it. else use a blank
StavFX
11/19/2020, 7:31 PMJoel
11/19/2020, 7:32 PMNir
11/19/2020, 7:44 PMNir
11/19/2020, 7:45 PMStavFX
11/19/2020, 8:22 PMif (foo?.str != null)
shouldn’t infer foo
to be non-nullNir
11/19/2020, 8:28 PMStavFX
11/19/2020, 8:29 PMclass Bar(val b: Bar? = null, val s: String? = null)
val bar: Bar? = null
if (bar?.b?.b?.b?.s != null) {
println(bar.b.b.b.s.length)
}
it compiles fine, but if tomorrow you decide “oh wait, it’s not just null, I want to make sure s
isn’t empty either”, you’ll lose all the smartcasting. So should bar.b.b.b
not have worked in the first place?Nir
11/19/2020, 8:36 PMStavFX
11/19/2020, 8:41 PM!bar?.b?.b?.b?.s.isNullOrEmpty()
for example.
Sure it can be avoided by a different combination of conditions, but I don’t think && would be very idiomatic in this caseNir
11/19/2020, 8:45 PMNir
11/19/2020, 8:46 PMNir
11/19/2020, 8:47 PMfoo?.str != null
, then effective ?.
is a built in function with foo
and str
(in a sense) as arguments; when the result is not null it applies the contract to the immediate argumentsStavFX
11/19/2020, 8:50 PM?.
function have a better contract than .isNullOrEmpty
?StavFX
11/19/2020, 8:52 PM!= null
have a better contract than isNullOrEmpty
Nir
11/19/2020, 8:59 PMNir
11/19/2020, 8:59 PMNir
11/19/2020, 9:00 PMNir
11/19/2020, 9:01 PMNir
11/19/2020, 9:06 PMStavFX
11/19/2020, 9:07 PMNir
11/19/2020, 9:09 PMNir
11/19/2020, 9:15 PMNir
11/19/2020, 9:16 PMStavFX
11/19/2020, 10:06 PMJoel
11/19/2020, 10:08 PMStavFX
11/19/2020, 10:09 PMNir
11/19/2020, 10:18 PMNir
11/19/2020, 10:19 PMNir
11/19/2020, 10:20 PM