Charles Flynn
08/17/2023, 2:57 PMval x: X = something()
if (x is A) return
// x should now smart cast to B
I'm guessing this just isn't supported. Do we know if K2 will be adding it?Joffrey
08/17/2023, 2:58 PMJoffrey
08/17/2023, 2:59 PMif
doesn't make use of special properties of B
, this addition of a C
subtype wouldn't fail compilation (but might change the behaviour of the program)Charles Flynn
08/17/2023, 3:01 PMCharles Flynn
08/17/2023, 3:04 PMCharles Flynn
08/17/2023, 3:04 PMMike Repec
08/17/2023, 3:42 PMwhen
is for though.
On the other hand, inverting your if
check will get your smart casting working how you want, albeit without the early exit and happy-path-left-alignment.
val x: X = something()
if (x is B) {
// x is now smart cast to B
}
You could handle the B case easily enough too in separate function to make it cleaner if you don't like the indent:
val x: X = something()
if (x is B) handleB(x)
...
fun handleB(b: B) {}
Joffrey
08/17/2023, 3:43 PMif (x !is B) return
for that matter - and that would be expressing the intent better if the point is to ensure that you have a B
instance after the if
(which would be resilient to addition of subtypes).Joffrey
08/17/2023, 3:44 PMin the 2 cases example adding C would cause it not to be able to cast to B anymore so it'd be a compilation errorThat is only if you actually use the fact that it's smart-cast to B after the
if
. But if you just do things assuming it's a B
, but without relying of type-safe properties of B
, it could compile fine but behave wrong.
My point is that such if
statements are dangerous because they don't account for future additions of subclasses, regardless of whether the compiler was able to smart cast or not. This is why I usually push for exhaustive `when`s over if
statements for these things, and also why we should avoid using else
in those `when`s. And in turn, it makes your problem with smart casting go away.Joffrey
08/17/2023, 3:51 PMif
of course, all I'm saying is that I don't find it that much of an issue in practice because the code pattern itself is fishy in the first place.