Home > database >  Why Dart holds *double standard* between `==` and `>=`
Why Dart holds *double standard* between `==` and `>=`

Time:01-08

I have two int values in Dart, test them equals or not with == previously, it was fine. Now I have to test if first one is greater or equals to the second one, so I changed == to >= instinctively, but it seems Dart was not happy with me doing that

  1. I double checked documentation of Dart, >= should work to test greater or equals operation
  2. IMO, in the end, if >= has something wrong, then the same should come to ==

enter image description here

enter image description here

CodePudding user response:

You are comparing two different operators which comes from different part of the Dart language. The == operator is defined on Object: https://api.dart.dev/stable/2.15.1/dart-core/Object/operator_equals.html

Which needs to be able to compare every type of object including null. The reason why the == operator does not have Object? as input parameter is because of the following detail in the Dart Language Specification (page 167) under the section "Equality":

Evaluation of an equality expression ee of the form e1 == e2 proceeds as follows:

  • The expression e1 is evaluated to an object o1.
  • The expression e2 is evaluated to an object o2.
  • If either o1 or o2 is the null object (17.4), then ee evaluates to true if both o1 and o2 are the null object and to false otherwise. Otherwise,
  • evaluation of ee is equivalent to the method invocation o1.==(o2)

...

https://dart.dev/guides/language/specifications/DartLangSpec-v2.10.pdf

So based on third rule, the language itself will make sure that null values are compared correctly and therefore the Object.== method will never see a null object as its input.


The other operator is >= and comes (in your case) from num which int extends from: https://api.dart.dev/stable/2.15.1/dart-core/num/operator_greater_equal.html

And is specified to accept only num (so int or double) which are a non-nullable type (null is therefore not allowed).

You are then trying to call the num.>= operator with the result from values?.length. This is a problem since values is nullable and can therefore potentially be null. And when you use the ?. operator, you are saying that if values are null, don't care calling .lenght but instead just return null.

So the type of values?.length ends up being int? which is not compatible with num.

  •  Tags:  
  • Related