and Then
Chain two computations together
If in a computation chain the result of one computation is needed as input for another computation, andThen
is there to chain the computations together.
Assume we have a result of fetching an user from a repository. We would like to send this user a notification, which in it self could fail as well.
With the following definitions.
data class User(val username: String, contactInfo: ContactInformation)
interface UserRepository {
fun fetchByUsername(username: String)
}
fun sendNotification(user: User): Result<NotificationProblem, Record> {
// implementation omitted
}
enum class NotificationProblem {
CouldNotFetchUser,
CouldNotSendNotification,
}
Sending a notification to a User
amounts to
val user: Result<NotificationProblem, User> = repository.fetchByUsername('dvberkel')
val record: Result<NotificationProblem, Record> = user.andThen(::sendNotification)
Or without intermediate variables
val record = repository.fetchByUsername('dvberkel').andThen(::sendNotification)
Return
the transformed value of a Success. Keeps the error otherwise.
Parameters
chain
Provides the transformed error