diff --git a/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Iterable.kt b/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Iterable.kt index 7fc7801..ad484b3 100644 --- a/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Iterable.kt +++ b/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Iterable.kt @@ -1,5 +1,45 @@ package com.github.michaelbull.result +/** + * Returns a list containing only elements that are [Ok]. + */ +public fun Iterable>.filterValues(): List { + return filterValuesTo(ArrayList()) +} + +/** + * Returns a list containing only elements that are [Err]. + */ +public fun Iterable>.filterErrors(): List { + return filterErrorsTo(ArrayList()) +} + +/** + * Appends the [values][Ok.value] of each element that is [Ok] to the given [destination]. + */ +public fun > Iterable>.filterValuesTo(destination: C): C { + for (element in this) { + if (element is Ok) { + destination.add(element.value) + } + } + + return destination +} + +/** + * Appends the [errors][Err.error] of each element that is [Err] to the given [destination]. + */ +public fun > Iterable>.filterErrorsTo(destination: C): C { + for (element in this) { + if (element is Err) { + destination.add(element.error) + } + } + + return destination +} + /** * Returns `true` if each element is [Ok], `false` otherwise. */ @@ -120,7 +160,7 @@ public fun Iterable>.combine(): Result, E> { * - Haskell: [Data.Either.lefts](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:lefts) */ public fun > getAll(vararg results: R): List { - return results.asIterable().getAll() + return results.asIterable().filterValues() } /** @@ -139,7 +179,9 @@ public fun Iterable>.getAll(): List { * * - Haskell: [Data.Either.rights](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:rights) */ -public fun > getAllErrors(vararg results: R): List = results.asIterable().getAllErrors() +public fun > getAllErrors(vararg results: R): List { + return results.asIterable().filterErrors() +} /** * Extracts from an [Iterable] of [Results][Result] all the [Err] elements. All the [Err] elements