I want to see if a variable is not of a certain type. I know I can do if(picture is XFile)
, but these both seem to work for the opposite:
if(picture !is XFile)
if(picture is! XFile)
What's the difference?
CodePudding user response:
void main() {
var myNum = 5;
if (myNum is! int) {
print('myNum is an integer');
}else{
print('not an integer');
}
}
output : not an integer
for the compiler it is same as is !int
void main() {
var myNum = null;
if (myNum is int) {
print('myNum is an integer');
}else{
print('not an integer');
}
}
output : not an integer
because the value is null
so is not an int
makes sens
void main() {
var myNum = null;
if (myNum !is int) {
print('myNum is an integer');
}else{
print('not an integer');
}
}
output : Uncaught TypeError: Cannot read properties of null (reading 'toString')Error: TypeError: Cannot read properties of null (reading 'toString')
for the compiler it is same as myNum! is
: the null safety
it is like if myNum
is null
throw an error
and do not check. Works as is
if myNum
is not null
.
CONCLUSION :
these both seem to work for the opposite : if(picture !is XFile) & if(picture is! XFile)
if we consider picture
is not null
we can write the two conditions like this :
if(picture is XFile)
if(picture is! XFile)
so they should work for the opposite
CodePudding user response:
x !is T
is not what you think it is. If you run dart format
on your code, you'll see that it's actually x! is T
; that is, it is using the post-fix !
operator, which asserts that x
is not null
, and then performs a normal is T
check (and therefore produce the opposite result than you expect). If x
is statically known to be non-nullable, dart analyze
should generate a warning about using the null-assertion operator unnecessarily.
Perhaps you mean to compare x is! T
and !(x is T)
. There is no logical difference between those expressions. There is a linter rule that suggests that is!
should be preferred, but it doesn't provide any explanation why. I believe it's because is!
ostensibly reads better ("is not") and is simpler than negating a parenthesized expression. (However, that stance predates null-safety, and arguably is!
might be more confusing now that there is a post-fix !
operator.)