本页尚未翻译,因此以英文显示。 参与翻译

repeat

Yields the same value n times — a lazy, finite source for padding and pairing.

Iterable<T> repeat<T>(int n, T value)

Lecture

repeat(n, value) yields value exactly n times, then stops — it's finite and lazy, like the rest of this section's generators. Note that it repeats the same value (or the same object reference, for non-primitives) every time; if you need a fresh value per iteration, generate it separately (e.g. with map over the result) rather than expecting repeat to call a factory function.

It's most useful paired with something else: zip it against a variable-length sequence to stamp a constant label onto every element, or use fx(...).join() to build a fixed-width separator string. repeat(0, value) is a valid, perfectly normal way to get an empty iterable.

If you actually want to repeat a whole sequence rather than one value — and keep going forever instead of a fixed n times — that's cycle, covered next.

Demo 1 · Basics

Demo 2 · Pairing a constant with a variable sequence

repeat yields the SAME value every time — pair it with zip to stamp a constant onto a variable-length sequence:

Try it yourself

Exercise: build a 5-item List<int> of the value 7 using repeat.

Related: range — a lazy sequence of increasing/decreasing integers · cycle — repeat a whole sequence, forever · zip — pairs repeat is often used with · fx — the chain repeat is usually wrapped in