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

0xf1f1

02/23/2024, 8:53 AM
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

Alejandro Serrano.Mena

02/23/2024, 8:54 AM
what is your goal here?
the main thing is that to "end with error" you need to use
raise
u

0xf1f1

02/23/2024, 8:55 AM
if the response is a success then create the report object, otherwise return a list of errors from the API
a

Alejandro Serrano.Mena

02/23/2024, 8:55 AM
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

0xf1f1

02/23/2024, 8:57 AM
that has worked, thanks. I am a bit confused with the return, should I removed the return from
return SomeType()
too ?
a

Alejandro Serrano.Mena

02/23/2024, 8:58 AM
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

0xf1f1

02/23/2024, 8:59 AM
yes, that is how I have done it thus far, its just the res.success condition has thrown me off
makes sense, thanks!