Skip to content

Allow non-const classes to be more efficient on const values #187

Open
@davidmorgan

Description

@davidmorgan

There are cases where we would like to do defensive copying only when a value is not const.

For example, an immutable list implementation might take a List as input. If the List is not const, it needs to make a defensive copy.

Currently only something that is itself const can be sure to receive const values. This is very restrictive. Lots of immutable collections, for example, use mutable internals for efficiency.

What is requested, then, is a way for non-const classes to know whether a value is const and behave differently. One feature that would satisfy this would be a way to specify an alternative constructor that is used when the values passed in are const:

class ImmutableList<T> {
  final List<T> list;
  
  // This will be called if `list` is `const`.
  ImmutableList(const List<T> list) : this.list = list;

  // This will be called if `list` is not `const`.  
  ImmutableList(List<T> list) : this.list = list.toList();
}

Further, 'auto const' would apply in these contexts, allowing:

ImmutableList([1, 2, 3])

to allocate a const list and avoid copying altogether.

The idea is just for illustration--the request is to give a way to avoid defensively copying const values.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhanced-constRequests or proposals about enhanced constant expressions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions