How do you extract the body from a ResponeEntity&l...
# spring
s
How do you extract the body from a ResponeEntity<> with type safety? getBody() has a
object?
signature, and you can work around this with
!!
. Is this the prefered method?
k
why not
?.
s
How would you structure that if you want to return the reponse from a method?
Copy code
fun doRequest(): User {
  restTemplate.exchange<User>(...).body!!
}
f
What if you use a default response? Something like
reesp?.boby : User()
m
Nullable type is returned for a reason. It means conversion can fail. In this case, you can return
User?
from doRequest method and let caller handle it or use something like
...body ?: DefaultUser()
.
Since this is a call to an external API, I prefer caller to handle an unexcpeted result. Also, you can use different model for external API response and your domain. That way, you can have a
sealed class
that has two variants:
User
or
Failure
. Similar to existing
Result<T>
class that Kotlin has, but it cannot be used (yet)
s
I'm using Either<> from Arrow, so I want to have the signature Either<Failure, User>, not Either<Failure, User?>.
m
Then you can say
if (user == null) Either.left(error) else Either.right(user)
or whatever the syntax is. Smart cast will know
user
in
else
it not null. That way, caller with get an error and handle it in some meaningful way.