dart-lang / dart-lang/language

Shorthand for creating constant identifier var (like an enum with a single value)

Open
#694 6 comments 0 reactions 0 assignees View on GitHub
enhanced-const feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

If I understood it correctly, this is what is being asked for in #183.

Sometimes I have required a constant value where I don’t care about the value, but I want it to be unique (as if it were a single value enum), so I create a var for the static type safety convenience. This has been useful for creating constant map keys or in #183 there is another use case. Currently this can be done either by creating an enum type (which can be a bit clumsy) or by defining a var:

`static var myIdentifier = Object()` (static when inside objects)

The drawback of this is that myIdentifier cannot be declared constant, it is a bit verbose and a prone to errors if forgetting to write `static`. It would be useful if it were possible to create constant identifiers like:

```dart
symbol id1, id2, id3;
Map map = {id1: 0};
foo(id1);
print(map[id3]); // prints '2'
...
foo(symbol id) {
map[id]++;
// id1 != id when symbol comes from the outside, only way that they can be equal is when foo(id1)
// is invoked from within foo
symbol id1;
map[id1] = 0;
map[id2] = map[id1] + 1;
map[id3] = map[id2] << 1;
}
```

`symbol` should be scoped as any var but it remains constant within the scope of a class or method.

I use the word symbol as an illustration, but I do not think it is appropriate as it conflicts with Symbol. When I required this feature I investigated and arrived to the Symbol type, however Symbol type didn’t make much sense to me, I think doing #mySymbol should just be a shorthand for creating a single word string, so `#mySymbol == 'mySymbol'`. I read a similar comment on #251. Would it be possible to change the Symbol behavior in future Dart releases?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.