Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide mapIfInstance? #105

Open
nikclayton opened this issue Jun 10, 2024 · 0 comments
Open

Provide mapIfInstance? #105

nikclayton opened this issue Jun 10, 2024 · 0 comments

Comments

@nikclayton
Copy link

nikclayton commented Jun 10, 2024

Here's an extension function that might be useful to include.

/**
 * Maps this [Result<V, E>][Result] to [Result<V, E>][Result] by either applying the [transform]
 * function to the [value][Ok.value] if this [Result] is [Ok&lt;T>][Ok], or returning the result
 * unchanged.
 */
public inline infix fun <V, E, reified T : V> Result<V, E>.mapIfInstance(transform: (T) -> V): Result<V, E> {
    contract {
        callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
    }

    return when (this) {
        is Ok -> (value as? T)?.let { Ok(transform(it)) } ?: this
        is Err -> this
    }
}

(that's using the 1.2x library version)

The motivating example is if you have a flow of Result where the OK value is one of a sealed set of subclasses and you typically only want to transform one of them. For example, Data.Loaded in this snippet:

sealed interface Data {
    data object Loading : Data
    data class Loaded(val data: String) : Data
}

sealed interface AppError {
    data class NetworkError(...)
    data class JsonError(...)
    // etc
}

Suppose you're processing a flow of Result<Data, AppError>

At the moment, with map, you have to write something like:

theFlow.map {
    when (it) {
        is Data.Loading -> it
        is Data.Loaded -> { /* some transform here */ }
    }
}

[Filtering the flow to just Ok(Data.Loaded) is not necessarily appropriate, as code "downstream" of the flow might still need to distinguish between these cases]

This rapidly gets tedious if you have to do this on every Flow<Result<V, E>>.

With this extension this becomes:

theFlow.mapIfInstance<_, _, Data.Loaded> { /* some transform here */ }

or

theFlow.mapIfInstance { it: Data.Loaded -> /* do something */ }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant