Marko Novakovic
01/24/2021, 9:02 AMEither
and Validated
together? Either
for fetching and Validated
for validating data. I have code that parses some data and then I need to perform some check on that data to determine is it valid or not. parsing function return Either
because parsing can fail and I want to validation function to return Validated
based on validation logicstojan
01/24/2021, 9:43 AMfun fetchData(): Either<Error, Success> = TODO()
fun validateData(s: Success): ValidatedNel<Error, ValidData> = TODO()
fun fetchAndValidate(): Either<Error, ValidData> =
fetchData.flatMap { success ->
validateData(success).toEither()
}
stojan
01/24/2021, 9:44 AMfetchData
as suspend
you can also use either {}
block instead of flatMap
stojan
01/24/2021, 9:45 AMMarko Novakovic
01/24/2021, 9:49 AMstojan
01/24/2021, 9:51 AMmapLeft
Marko Novakovic
01/24/2021, 9:51 AMstojan
01/24/2021, 9:52 AMsealed class MyErrors {
object ParseErrors : MyErrors()
object ValidationError : MyErrors()
}
stojan
01/24/2021, 9:52 AMMarko Novakovic
01/24/2021, 1:12 PMfold
at the end of the chain error is Any
stojan
01/24/2021, 1:13 PMstojan
01/24/2021, 1:13 PMAny
Marko Novakovic
01/24/2021, 1:14 PMAny
Marko Novakovic
01/24/2021, 1:15 PMThrowable
still nothingstojan
01/24/2021, 1:16 PMMarko Novakovic
01/24/2021, 1:18 PMfun List<String>.parseData(): Either<Throwable, List<Data>> = TODO()
fun List<Data>.validate(): ValidatedNel<Throwable, List<Data>> = TODO()
fun main() {
readData()
.flatMap(List<String>::parseData)
.flatMap { data -> data.validate().toEither() }
.fold(
{ /// it is Any },
{},
)
Marko Novakovic
01/24/2021, 1:19 PMMarko Novakovic
01/24/2021, 1:25 PMparseData
it still gives me Any
as error type if I set it to something other than Throwable
Marko Novakovic
01/24/2021, 1:28 PMflatMap(List<String>::parseData)
and folding over Validate
inside either’s rightstojan
01/24/2021, 1:40 PMValidatedNel
, which is a typealias for Validated<Nel<E, A>>
so the errors don't match here Throwable
from the parseData
and List<Throwable>
for validate()
stojan
01/24/2021, 1:41 PMValidated
instead of ValidatedNel
it should work
I used ValidatedNel
in the example because it's usually used when you want to collect ALL validation errors in a listMarko Novakovic
01/24/2021, 1:42 PMValidatedNel
?stojan
01/24/2021, 5:19 PMmapLeft
stojan
01/25/2021, 9:44 AMsealed class Error
data class FetchError(val t: Throwable) : Error()
data class ValidationError(val t: List<Throwable): Error()
fun fetchData(): Either<Error, Success> = TODO()
fun validateData(s: Success): ValidatedNel<Error, ValidData> = TODO()
fun fetchAndValidate(): Either<Error, ValidData> =
fetchData.
.mapLeft<Error> { FetchError(it) }
.flatMap { success ->
validateData(success).toEither()
.mapLeft { ValidationError(it) }
}