Can someone help me structure the following code p...
# arrow
u
Can someone help me structure the following code properly:
fun mkReport(res: Response): EitherNel<Error, SomeType> = either {
when (res.success) {
true  -> return SomeType()
false -> {
val ee: List<String> = res.errors
return ee.map { Error(it) }
.toNonEmptyListOrNull()!!
}
}
}
The false condition fails with the following error:
Type mismatch.
Required:
EitherNel<Error, SomeType>
Found: NonEmptyListError
a
what is your goal here?
the main thing is that to "end with error" you need to use
raise
u
if the response is a success then create the report object, otherwise return a list of errors from the API
a
Copy code
fun mkReport(res: Response): EitherNel<Error, SomeType> = either {
  if (success) {
    SomeType()
  } else {
    val errors = res.errors.map { Error(it) }.toNonEmptyListOrNull()!!
    raise(errors)
  }
}
1
some notes: • because you are inside the lambda in
either
, you should not use
return
• you use
raise
to specify that you want to end in error
u
that has worked, thanks. I am a bit confused with the return, should I removed the return from
return SomeType()
too ?
a
there's also another way in which you specify conditions in which you continue
Copy code
fun mkReport(res: Response): EitherNel<Error, SomeType> = either {
  ensure(res.success) {
    res.errors.map { Error(it) }.toNonEmptyListOrNull()!!
  }
  SomeType()
}
1
about the
return
, this is not particular to Arrow, but the general difference between
Copy code
fun f() = 3 // no return
fun f() { return 3 } // return needed
1
u
yes, that is how I have done it thus far, its just the res.success condition has thrown me off
makes sense, thanks!