このページはまだ翻訳されていないため、英語で表示されます。 翻訳に参加する

always

Returns a function that always returns the same fixed value, ignoring its argument.

T Function([Object? _]) always<T>(T a) => ([Object? _]) => a;

Lecture

always(a) closes over a and hands back a function that discards whatever it's called with and returns a every time. The optional parameter is the trick that makes it fit anywhere a unary callback is expected — a mapper, an orElse handler, a fallback branch — without you writing (_) => a by hand each time.

It's the constant counterpart to identity: identity passes the input through, always throws it away. Both are plain synchronous functions with no async variant or chain form.

Demo 1 · Basics

Note the optional argument — greet(123) still returns 'hi', which is what lets it act as a map callback:

Demo 2 · Constant fallback in a dispatch table

always is a natural fit for orElse in cases — a fixed default that doesn't need to look at the unmatched value:

Try it yourself

Exercise: use always to replace every score in this list with the string 'graded'.

Related: identity — pass the argument through instead · cases — dispatch table that often pairs with always as orElse · when — conditional transform, value-in value-out · memoize — cache a computed value instead of a constant one