In the example: `Validated.applicative<KnownEr...
# arrow
c
In the example:
Copy code
Validated.applicative<KnownError>().map(vId, vName, vAge, { (id, name, age) ->
  Person(id, name, age)
}).ev()
Would it be fair to say that Applicative is ‘just' a generalization of
flatMap
that allows to call it on multiple objects? Maybe something like
Copy code
vId.flatMap { id ->
  vName.flatMap { name ->
    vAge.flatMap { age ->
      Person(id, name, age)
    }
  }
}
Or is that completely wrong?
s
That assumption is incorrect.
flatMap
is used to sequence dependent operations. In this case the next function cannot execute if the previous failed. Whilst in your original example that is not the case. i.e.
Copy code
getUserById(id).flatMap { user ->
  fetchInfoForUser(user).flatMap { info ->
    process(info)
   }
}
This is also the reason why you will not find
flatMap
on.
Validated
since then the behaviour would be identical to
Either
.
Whilst
mapN
offers a way to combine indepent operations. Which means you can run them independently of each-other, and in the case of
ValidatedNel
combine the results. But for the case of
Either
, that logic is implemented by
flatMap
since there we want to short-circuit on errors.
So actually it was only partial incorrect, since for some data types such as
Either
it simply delegates to
flatMap
but that's not the case for all implementors of
Applicative
.
c
Oh, so in the case of Validated, if it was implemented with flatMap it would not be able to accumulate errors, so instead it's implemented in another way that acts as a flatMap but inside the implementation it can still accumulate errors?
s
Yes, exactly. Actually
Validated
doesn't even have
flatMap
As you can see in the code for
Either
map
is implemented over
flatMap
, and in the case of
Validated
you can see that it's implemented over
bimap
. So
Validated
doesn't short-circuit like
Either
does, which allows the accumulations of errors.
That's also why you have to provide
Semigroup<E>
for
Validated.applicative
and you don't have to do so for
Either
. Since
Validated
can continue on errors, and
Either
can't.
c
Thanks a lot 👍 that makes a lot of sense now