Skip to content

[patterns] Object pattern with redirecting factory constructors #3159

Closed as not planned
@dnys1

Description

@dnys1

I searched the issues and couldn't find a related discussion, but apologies if I missed it. I'm wondering if there has been consideration for allowing factories in destructure/object patterns?

A motivating example for this is the following sealed class hiearchy:

// shape.dart
import 'dart:math';

sealed class Shape {
  const Shape();

  const factory Shape.circle(double radius) = _Circle;
  const factory Shape.square(double side) = _Square;
}

final class _Circle extends Shape {
  const _Circle(this.radius);

  final double radius;
}

final class _Square extends Shape {
  const _Square(this.side);

  final double side;
}

// main.dart
void main() {
  final Shape shape = Shape.circle(2.0);
  final area = switch (shape) {
    Shape.circle(:final radius) => radius * radius * pi,
    Shape.square(:final side) => side * side,
  };
}

While it's certainly possible to just make Circle and Square public, the beauty of redirecting factories IME is that it improves the discoverability of subclasses in ADTs, where the enumeration of all values is visible on the base class. It would be great if, in the same way these classes are constructed, they could likewise be destructured which would reduce confusion and developer cycles.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions