https://kotlinlang.org logo
#announcements
Title
# announcements
s

sxtanna

06/04/2019, 2:09 AM
Is there a reason this doesn't function in this way?
seems kinda odd
s

streetsofboston

06/04/2019, 2:28 AM
In your example, !Some is just None. But in general, an 'is' check always narrows the type-cardinality to at most one value (smart type checking is possible), a '!is' check narrows the type-cardinality to just one less value, which is usually larger than one. This means '!is' cannot have smart type checking. Also, say you add an extra sub-type to your sealed hierarchy. Then your code would no longer compile. Only 'when' can be exhaustive, 'if' cannot be. The reason that the code after your 'if' statement compiles is because now 'is Some' is true and that narrows type to just one possible value and smart type checking is possible.
s

sxtanna

06/04/2019, 3:18 AM
Well I knew why the second part worked, I was just wondering why the functionality for the strict type resolution wasn't present. If I were to go and add another sub type, that would be my own fault, and that would be on me to update the code else where.
It's the same logic when adding another enum constant when you have already exhaustive when statements in your code.
s

streetsofboston

06/04/2019, 3:46 AM
The
!is
does not work in a(n exhaustive)
when
either. I guess that the pattern matching on the
when
doesn’t work with
!is
, maybe because it is in general too hard to find the commonalities between possibly more than one sub-types of a sealed class. I can imagine that the language doesn’t make an exceptions even if the
!is
results in only one sub-type
s

sxtanna

06/04/2019, 4:43 AM
This doesnt seem like something that would be super complicated to have implemented
s

Stephan Schroeder

06/04/2019, 9:20 AM
it’s not for the binary case, but you could e.g. define a whole new sealed subclass hierarchy inheriting from Result and even though the compiler could still figure it out it’d be non-obvious for the programmer. Or you start of as binary and later down the line someone adds a third option and suddenly your
!is
catches more than intended.
3 Views