Reputation: 5532
There is a Person class, and an extension of the Person class, as follows:
class Person {
bool get isEmpty{
return this == null;
}
}
extension PersonExt on Person {
bool get isEmptyByExt {
return this == null;
}
}
The call is as follows:
Person person;
var result = person.isEmptyByExt;
print(result);
var result2 = person.isEmpty; // ERROR
print(result2);
person.isEmptyByExt;
There is no problem with the call;
but person.isEmpty;
will report an error here:
NoSuchMethodError: The getter 'isEmpty' was called on null.
Receiver: null
Tried calling: isEmpty
Why?
Upvotes: 1
Views: 2354
Reputation: 90175
Calling an instance method involves virtual dispatch and requires an actual object instance for inheritance and method overrides to work at runtime. It never makes sense for this
to be null
in an instance method.
Extension methods are syntactic sugar for static functions to make them look like instance methods. That is:
extension PersonExt on Person { bool get isEmptyByExt { return this == null; } }
is essentially equivalent to:
class PersonExt {
static bool isEmptyByExt(Person _this) {
return _this == null;
}
}
They work on the static (known at compile-time) type of the object and not the object's actual runtime type. (This is why extension methods can't work on dynamic
types, and they cannot be overridden by derived classes.) Since they're the equivalent of a static
function, the object could be null
.
Note that this is a bit clearer with null-safety enabled, where there is a distinction between:
extension PersonExt on Person
(this
cannot be null
)extension PersonExt on Person?
(this
can be null
).Further reading: Dart Extension Methods Fundamentals
Upvotes: 2