Clarification on avoid_null_checks_in_equality_operators linter rule - dart

There is a linter rule which verifies that one don't check for null equality in the overridden == operator.
The rule is here.
I understand this rule but can't see how it is realized technically.
It seems that Dart itself makes some implicit check on other != null and == returns false in this case. Is this correct?
In other languages, e.g. Java, one needs to explicitly add this check in the overridden equals.
Second question is why then it does not check automatically on the type of other as well. Why it is ok to spare me as a programmer from checking on null, but I still need to check if other is Person? Are there cases when one overrides == and checks there for some other type then the type of that class?

The linter rule implementation is simple, it just checks whether you compare the argument of operator == to null.
The reason you don't need to is that e1 == e2 in Dart is defined to first evaluate e1 and e2 to a value, then give a result early if one or both of the values is null, and only otherwise it calls the operator== method on the value of e1.
So, when that method is called, you know for certain that the argument is not null.
The reason the == operator doesn't do more checks before calling the operator== method is that there are examples where that would be wrong.
In particular, int and double can be equal to each other. Having instances of different classes potentially being equal to each other is more common that you'd think (proxies, mocks, wrappers, Cartesian point vs polar point, int vs double).
The other check you could potentially do early is to say that an object is equal to itself, so if (identical(this, other)) return true;, but there is one counter-example forced upon the language: NaN, aka. double.nan. That particular "value" is not equal to itself (which breaks the reflexivity requirement for ==, but is specified that way by the IEEE-754 standard which is what the CPUs implement natively).
If not for NaN, the language would probably have checked for identity before calling operator== too.

It seems that Dart itself makes some implicit check on other != null and == returns false in this case. Is this correct?
Yes.
Second question is why then it does not check automatically on the type of other as well. Why it is ok to spare me as a programmer from checking on null, but I still need to check if other is Person? Are there cases when one overrides == and checks there for some other type then the type of that class?
It's less common, but there can be cases where you might want to allow a different type on the right-hand-side of the equality. For example, the left-hand-side and right-hand-side might be easily convertible to each other or to a common type. Imagine that you created, say, a Complex number class and that you wanted Complex(real: 4.0, imaginary: 0.0) == 4 to be true.

From the doc:
no class can be equivalent to [null]
Meaning, when other is Person is true, then other != null is also true. This is because:
The null object is the sole instance of the built-in class Null.
(https://dart.dev/guides/language/spec)
So every instance check against any type but Null will return false for null:
class A {}
void main() {
final x = null;
final a = A();
print(x is Null); // true
print(x is A); // false
print(a is Null); // false
print(a is A); // true
}

Related

Lua nonsense to find if something is nil

There seems to be a difference between these two checks:
if not object then
if type(object) == "nil" then
However I really don't understand the difference.
if type is "nil", shouldn't a not object then also work?
Lua, like many other dynamically typed languages, has the concept of "truthy" and "falsy", where boolean expressions can handle more values than just actual booleans.
Each non-boolean value has a specific meaning attached when used in a boolean expression. Specifically:
nil and false are "falsy"
everything else is "truthy"
That is why (not nil) == (not false), but type(nil) ~= type(false), because not x is a boolean expression that coerces x to truthy/falsy, while type() checks the actual type.

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

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
I double checked documentation of Dart, >= should work to test greater or equals operation
IMO, in the end, if >= has something wrong, then the same should come to ==
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.

How check type reference - dart

If I have a object like this:
class MyClass<K>{...
How I could check type of K? If was a variable was easy,
ex:
(myVar is Object)... //true | false
But in my case, this dont works:
(K is Object) // awalys false
You want == here. Using is is for comparing the type of variable, not a literal type.
This will only check if K is actually Object if you use K == Object. If you pass K as int for instance, it will not be considered to be an Object.
I recommend not using == for comparison of Type objects. It only checks exact equality, which might be useful in a few situations, but in plenty of situations you do want a subtype check.
You can get that subtype check using a helper function like:
bool isSubtype<S, T>() => <S>[] is List<T>;
Then you can check either isSubtype<K, Object> to check if K is a subtype of Object (which is true for everything except Null and types equivalent to Object?, but that can also be checked like null is! K), or isSubtype<Object, K> to check whether K is a supertype of Object.
It has the advantage that you can compare to any type, not just types you can write literals for. For example K == List only works for List<dynamic>. If you need to check whether K is a List<int>, you can do isSubtype<K, List<int>>.
You can get equivalence of types (mutual subtype), without requiring them to be the same type, by doing isSubtype in both directions. For example isSubtype<Object?, dynamic>() and isSubtype<dynamic, Object?>() are both true, but if K is Object? then K == dynamic is false.

why identical() return true on two strings

I'm new to Dart. The documentation say: "To test whether two objects x and y represent the same thing, use the == operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.)"
So, if type this code:
var foo = 'bar';
var baz = 'bar';
print(identical(foo, baz));
If i've well understood, foo and bar do not reference the same object. So identical() must return false, isn't it ?
But it's not the case, at least in DartPad.
Where is the problem.
In this case foo and bar do reference the same object.
That is because the compiler canonicalizes string literals.
The specification requires most constants to be canonicalized. If you create const Duration(seconds: 1) in two places, it will become the same object. Integers, doubles and booleans are always canonicalized, whether constant or not (the language pretends that there is only one instance per value).
Strings are special in that the specification is not entirely clear on whether they need to be canonicalized or not, but constant strings need to be canonicalized for constants to make sense, and all the compilers do that.
A literal is a constant expression, so string literals are always canonicalized. That means that 'bar' denotes the same object no matter where it occurs in your code.
For several built-in "literals", you will always get identical true for equal values.
bool
String
int
double (I think)

How to return a single value with edge cases in Swift?

Should I return a optional value like:
func someFunc(#num: Int) -> Obj? {
if num < 0 {
return nil
}
...
}
Or just use assert:
func someFunc(#num: Int) -> Obj {
assert(num >= 0, "Number should greater or equal then zero")
...
}
Edit: Now the conditions are identical in two cases, the number should greater or equal then 0. Negative values are not permitted.
If you use assert and the caller passes an invalid argument it is a non-recoverable error/crash. The caller may not be aware of all the ways the assert may be caused, that is internal logic the caller is not supposed to know.
Really the only time assert is meaningful is to check the calling arguments on method entry and even in that case it must be made clear to the user exactly what is invalid and that can never be made more stringent for the life of the method.
Since this is about Swift returning an Optional seems to make the most sense and it will be clear to the caller that a possible error must be handled. Optionals are a major feature of Swift, use them.
Or always return a useful result the way atan() handles being called with ±0 and ±Inf.
It depends on what you want the precondition of the function to be: if it is an error call it with a negative value (or non-positive; your two examples are contradictory), then go with the assert and document this. Then it becomes part of the contract that the user of the function must check the value if it's uncertain. Or if it makes more sense to support these values and return nil (e.g., the function will typically be called with such values and the nil is not an issue for that typical use), do that instead… Without knowing the details it's impossible to tell which suits best, but my guess would be the former.

Resources