I want to compute the depth of a recursive object in Dart (kind of tree). Root node has a null
as its parent.
class MyNode {
MyNode? parent;
int get depth => 1 + ((parent == null) ? -1 : parent.depth);
}
This code should return 0 for the root node, 1 for roots children and so on. But it does not compile due to error
A value of type 'double' can't be returned from the function 'depth' because it has a return type of 'int'.
How to rewrite method depth
to work as expected?
Dart version is 3.1.3
I am not sure I understand the error message you are getting since that does not seems right. But the error message you should get are the following on your parent.depth
call:
class MyNode {
MyNode? parent;
int get depth => 1 + ((parent == null) ? -1 : parent.depth);
// The property 'depth' can't be unconditionally accessed
// because the receiver can be 'null'.
}
Reason being that even if you have checked if parent
might be null
, in theory you could have replaced this variable with a getter in a subclass which does not return the same value every time you request the value.
Instead, I suggest rewrite the code to the following:
class MyNode {
MyNode? parent;
int get depth => 1 + (parent?.depth ?? -1);
}
Here we make use of two null-aware operators, ?.
and ??
:
parent?.depth
means that if parent
is null
, we will just return null
. If parent
is not null
, we return the value of calling parent.depth
.??
means that if the left-side are null
, we use the value to the right. Otherwise, we use the value to the left.So parent?.depth ?? -1
ends up meaning that if parent
are null
, we use the -1
value. Otherwise, we use the value of parent.depth
. And all of this can be done without ending up asking parent
twice about it being null
and it is therefore safe to do so.