add

Adds two values of the same type, as a function you can pass around.

T add<T extends Object>(T a, T b) => (a as dynamic) + b as T;

Lecture

add(a, b) is + packaged as a function value. Since it dispatches to + dynamically, it works for anything that supports the operator — num, String concatenation, even List concatenation — mirroring FxTS's add, which accepts both numbers and strings.

Its real value shows up wherever an API wants a binary (T, T) -> T function rather than an inline (a, b) => a + b — most naturally as the combining function for reduce/fold. It's a binary function though, so to use it as a unary map callback (adding a fixed amount to every element) you close over one side yourself: (b) => add(n, b).

Demo 1 · Basics

Demo 2 · As a reducer, and closed over for map

Try it yourself

Exercise: use fold + add to concatenate all the parts into one string.

Related: reduce / fold — the usual home for add as a combiner · sum — a ready-made sum for Iterable<num> · gt · gte · lt · lte — the comparison counterparts to add · apply — call any function with a dynamic argument list