https://kotlinlang.org logo
#arrow
Title
# arrow
d

Davide Giuseppe Farella

03/21/2023, 5:22 PM
Hello people, is there a way to “merge” 2 validated? E.g. given two
Validated<A, B>
, if they were
Either
I would do, for example
Copy code
either {
  val a = eitherA.bind()
  val b = eitherB.bind()
  Combine(a, b)
}
What’s the right way to do it with
Validated
? Either with the
either
block or any other solution 🙂
solved 1
p

phldavies

03/21/2023, 5:35 PM
You would normally use the
zip
extension for this but you'd need to provide some way of merging
A
in case both were invalid. Usually this is covered by using
ValidatedNel<A, B>
(a typealias for
Validated<NonEmptyList<A>, B>
)
d

Davide Giuseppe Farella

03/21/2023, 5:37 PM
Thank you for the answer. Could you please provide a real example, considering two
Validated<String, Int>
? 🙂
I’m not very familiar with different types than
Either
, so I’m struggling to understand how to use it
p

phldavies

03/21/2023, 5:38 PM
How would you want to merge the two error Strings?
d

Davide Giuseppe Farella

03/21/2023, 5:38 PM
Let’s concatenate them
Or just provide an example with the
ValidateddNel
, I just need an example of how to use
zip
, then I’ll take it from there 🙂
p

phldavies

03/21/2023, 5:42 PM
Regarding that, with Arrow 1.2.x onwards,
Validated
is going to be deprecated, and removed from Arrow 2.0.0 to simplify this.
d

Davide Giuseppe Farella

03/21/2023, 5:44 PM
Oh, I see! So I’ll just use Either?
p

phldavies

03/21/2023, 5:44 PM
For
ValidatedNel
it's relatively simple to use
.validNel()
and
.invalidNel()
to construct your values much like you would
.valid()
and
.invalid()
. Once you have two values you can join them using
a.zip(b) { validA, validB -> doSomethingWith(validA, validB) }
With 1.2.x and above there'll be an
zipOrAccumulate
set of functions that will provide the same logic (combining one or more lefts, or providing all rights to a function)
d

Davide Giuseppe Farella

03/21/2023, 5:46 PM
Ok. Thank you so much!
With
ValidatedNel
I felt less stupid and everything worked straight away 🙂
p

phldavies

03/21/2023, 6:01 PM
With
Validated<A, B>
you need to provide an additional argument to zip of a
Semigroup<A>
(which is effectively just a function
A.(A) -> A
like
String::plus
) With a custom combine to comma-delimit errors you can have
Copy code
lateinit var a: Validated<String, Int>
lateinit var b: Validated<String, Int>

fun String.combine(other: String) = "$this, $other"

a.zip(String::combine, b) { validA, validB -> validA + validB }
d

Davide Giuseppe Farella

03/21/2023, 6:10 PM
I see! Thanks again!
2 Views