mapCatching for Collections in Standard Library?

Hello Kotlin Community,

I came across this extension method on Result in the Standard Library:

fun <T, R> Result<T>.mapCatching(transform: (T) -> R): Result<R>

The name mapCatching suggests there would be a similar operation on collections, but there does not appear to be an equivalent for Iterable.

I use wrote my own quick extension to get this behavior, but I’m wondering if this semantic is something that could be included in the Standard Library?

fun <T, R> Iterable<T>.mapCatching(mapper: (T) -> R): List<Result<R>> = this.map {
    try {
        Result.success(mapper(it))
    } catch (ex: Throwable) {
        Result.failure(ex)
    }
}

This is especially useful in my project for tight mapping loops which can throw exceptions. My specific use-case is deserializing arbitrary JSON into data classes which may fail validation. This little method greatly helps filter for the successes in a very declarative way, and I think this would be used often enough to merit this addition to the Standard Library. Thoughts?

“map” has much wider meaning than collections only.

Mapping a collection while catching exceptions into a Result object seems to me like a very specific need. Not very common and still it can be done relatively easy:

list.map { runCatching { doSomething(it) } }

Also note that Result is not meant to replace exception handling or domain classes for storing results of some operation. It has its uses, but it shouldn’t be overused. Utilities for collections would probably make people use it for everything.

3 Likes

Thanks for the constructive feedback. You’re correct that this was a very simple thing to implement, and I like your take on a different approach to the same solution as well!

After reading the comment about Result, I decided to do some more digging and found this thread: State of Kotlin.Result vs. kotlin-result? - #4 by Ilmir.Usmanov . It seems like the future of Kotlin Result and its use-cases is uncertain, so I’m willing to admit that this mapCatching suggestion may not be the correct thing to add to the standard library after all.