Skip to content

Type promotion issue with nullable functions #60632

Closed as duplicate of#1536
Closed as duplicate of#1536
@nielsenko

Description

@nielsenko

Here is a condensed example of the problem.

typedef Func = int Function(int);
Func weird(Func? functor) {
  functor ??= (_) => 42; // functor cannot be null hereafter
  return (int i) {
    return functor!(i); // yet, why is ! needed here?
  };
}

Even moving the promotion inside the returned function fails:

typedef Func = int Function(int);
Func weird(Func? functor) {
  return (int i) {
    functor ??= (_) => 42; // functor cannot be null hereafter
    return functor!(i); // yet, why is ! needed here?
  };
}

But this works:

Func weird(Func? functor) {
  functor ??= (_) => 42; // functor cannot be null hereafter
  return functor; // <-- this works;
  // return functor!; // <-- this correctly warns that ! will have no effect
}

and this as well:

Func weird(Func? functor) {
  final f = functor ?? (_) => 42; // f cannot be null
  return (int i) {
    return f(i); // Tada 🎉 
  };
}

dart info

#### General info

- Dart 3.7.2 (stable) (Tue Mar 11 04:27:50 2025 -0700) on "macos_x64"
- on macos / Version 15.4 (Build 24E248)
- locale is en-DK

#### Project info

- sdk constraint: '^3.7.2'
- dependencies: 
- dev_dependencies: lints, test

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-dart-modelFor issues related to conformance to the language spec in the parser, compilers or the CLI analyzer.model-flowImplementation of flow analysis in analyzer/cfe

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions