Skip to content

Closures should not close over unnecessary variables. #47981

Closed
@mmcdon20

Description

@mmcdon20

In #47972 @lrhn said there was probably already an issue for this, but I couldn't find it, so apologies if this is a duplicate.

If closures only closed over variables that are actually used inside the closure, it would make working with Isolates easier.

As of dart 2.15 Isolate.spawn can accept a closure, but will fail at runtime if one of the variables it closes over is one of the non supported message types like a ReceivePort, or UserTag. The program will fail even if the variable is never used within the closure itself.

Consider this example program.

import 'dart:isolate';

void main() async {
  final receivePort = ReceivePort();
  int three = 3;
  await Isolate.spawn(
    (SendPort port) => Isolate.exit(port, [1, 2, three]),
    receivePort.sendPort,
  );
  print(receivePort.first);
}

Which fails at runtime with the error message:

Unhandled exception:
Invalid argument(s): Illegal argument in isolate message: (object is aReceivePort)

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-vmUse area-vm for VM related issues, including code coverage, and the AOT and JIT backends.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions