tezvyn:

map versus compactMap versus flatMap

Source: interviewintermediate

WHAT IT TESTS: functional transforms on sequences. OUTLINE: map transforms each element one-to-one; compactMap transforms then drops nils; flatMap transforms to sequences then concatenates.

WHAT IT TESTS: precise grasp of three commonly confused higher-order functions. ANSWER OUTLINE: map applies a closure to every element and returns a same-length array; compactMap applies a closure returning an Optional and discards the nil results, unwrapping the rest; flatMap on a sequence applies a closure returning a sequence and concatenates the results into one flat array. RED FLAG: saying flatMap filters nils, which was its old overload now deprecated in favor of compactMap.

Read the original → interview

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

map versus compactMap versus flatMap · Tezvyn