Description
Static functions are compile time constants, but function literals are not.
It would be great if it was possible to write compile time constant function literals. They would necessarily have static scope (no access to "this") even if written inside a class declaration.
Constant function literals would create only one function object per function expression (no unification of different function expressions, even if they happen to have the same body).
This is particularly useful for default function parameters.
I suggest const <functionLiteral>
as syntax. That would allow you to write, e.g.,:
class Map<K,V> {
V getIfPresent(K key, [V onNotPresent() = const () => null]);
}
The current alternative is to declare the function as static:
class Map<K,V> {
V getIfPresent(K key, [V onNotPresent() = _returnNull]);
static _returnNull() => null;
}
You can use it to ensure that you don't create too many closures if you want to create a function inside a loop:
for (var x in xs) {
x.somethingOrError(const (x) => throw new Failure(x));
}
which would otherwise create a new closure per iteration of the loop. The alternative is again to define a static function somewhere and use that, but it moves the logic away from where it's most readable.
The syntax shouldn't collide with any current use of "const", since we currently don't allow that syntax in expression position. It does collide with a constant constructor declaration, but the uses are different enough that I don't think it's a problem. If we want parity, we could allow const foo() => xx
as a top-level declaration too, meaning the same as static
, but that would make static
redundant.