-
Notifications
You must be signed in to change notification settings - Fork 65
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
Add tryRecoverIf and tryRecoverUnless functions #94
Conversation
Could you give an example use-case where this would be used? The naming is a little misleading currently, a function prefixed with |
For example you try to get data from repository, don't get it and try to fetch data from remote service: |
I think the names could actually be Let me know if you disagree or come to a better name. If we look at the symmetry between public inline infix fun <V, E, U> Result<V, E>.map(transform: (V) -> U): Result<U, E> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Ok -> Ok(transform(value))
is Err -> this
}
}
public inline fun <V, E> Result<V, E>.recoverIf(predicate: (E) -> Boolean, transform: (E) -> V): Result<V, E> {
contract {
callsInPlace(predicate, InvocationKind.AT_MOST_ONCE)
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Ok -> this
is Err -> if (predicate(error)) {
Ok(transform(error))
} else {
this
}
}
} Then we look at the public inline infix fun <V, E, U> Result<V, E>.andThen(transform: (V) -> Result<U, E>): Result<U, E> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Ok -> transform(value)
is Err -> this
}
} If we apply the symmetry from the first snippet to the public inline infix fun <V, E, U> Result<V, E>.andThenRecoverIf(predicate: (E) -> Boolean, transform: (E) -> Result<U, E>): Result<U, E> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Ok -> this
is Err -> if (predicate(error)) {
transform(error)
} else {
this
}
}
} Which is identical to your This would result in your example producing the following code: userRepository
.find(userId)
.andThenRecoverIf({ it is NotFoundError }) { userMasterSystem.getById(userId) } |
|
Yeah I think that makes sense. I feel like the lib is quickly exploding with the |
5961410
to
e3bddef
Compare
f36d79d
to
05a1e91
Compare
db77fe3
to
dfab2bd
Compare
Seems like one of the tests has failed on macos-11 |
dfab2bd
to
e5753b3
Compare
Yes, I missed it, thank you! Hope no errors now =) |
Merged in d4414b1 |
Sometimes there is a need to recover certain errors and this recovery may produce an error on its own. Existing recoverIf function doesn't fit this case because the result of transformation is wrapped in Ok. Added tryRecoverIf and tryRecoverUnless for the described case.