You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classEvent {}
classEventSubscription<TextendsEvent> {}
typedefEventHandler<TextendsEvent> =voidFunction(T);
EventSubscription<T>?on<TextendsEvent>(EventHandler<T> handler) {
returnnull;
}
voidadd(EventSubscription<Event>? event) {}
classChildEventextendsEvent {}
voidmain() {
// Inline call errors with:// "The argument type 'void Function(ChildEvent)' can't be assigned to the parameter type 'void Function(Event)'"add(on((ChildEvent event) {}));
// But if I split it up:final x =on((ChildEvent event) {});
add(x); // OK
}
Observed behavior:
When I call add(on(...)) inline with a ChildEvent handler, I get a type error in Dart: “The argument type 'void Function(ChildEvent)' can’t be assigned to the parameter type 'void Function(Event)'.”
However, if I store the result of on((ChildEvent event) {}) in a local variable and then pass that variable to add, it compiles without error.
Expected behavior:
I would expect consistent type checking. Either both ways should fail if EventSubscription isn’t assignable to EventSubscription, or both ways should succeed if an implicit cast is valid. It’s confusing that Dart’s type system errors on the inline approach.
Environment:
Dartpad: Based on Dart SDK 3.7.2 and Flutter SDK 3.29.2
The text was updated successfully, but these errors were encountered:
When given as argument to add, the on call has a context type of
EventSubscription<Event>?
That guides type inference making on return an EventSubscription<Event> and therefore binds T to Event.
Thats the least restrictive binding that can work in this context, so it should be fine.
When assigned to an untyped variable, type inference doesn't get a context to guide inference of T on the way down, so it continues inferring the arguments, and tries to infer a T from those, making it ChuldEvent.
The problem here is that T occurs contravariantly in the parameter type of on, so the "least restrictive" binding of T is actually the most restrictive for that parameter. That's why you get an error after downwards inference has decided to use Event for T.
Observed behavior:
When I call add(on(...)) inline with a ChildEvent handler, I get a type error in Dart: “The argument type 'void Function(ChildEvent)' can’t be assigned to the parameter type 'void Function(Event)'.”
However, if I store the result of on((ChildEvent event) {}) in a local variable and then pass that variable to add, it compiles without error.
Expected behavior:
Environment:
The text was updated successfully, but these errors were encountered: