Hey everyone! Today I finally started using sealed...
# announcements
p
Hey everyone! Today I finally started using sealed classes, which is great. But I came to a point where I'm not sure how to handle it in the correct way:
Copy code
.map { (payment, requestModel) -> steps.performRequest(payment, requestModel) 
.filter { (_, result) -> result is ApiResult.Success }
.map { (payment, result) -> steps.update(payment, result) }
After performing the request, I want to filter out all results which were not of Type
ApiResult.Success
Unfortunately the compiler does not allow this, since
update()
is expecting
ApiResult.Success
. What did I miss there? My only solution right now is to set the
result
Parameter to ApiResult and add a
require()
block in my update function, but I'm not really happy with that.
g
p
I totally forgot about that. Thanks! But forwarding to that: I'm returning
Pair<Payment, ApiResult>
, that method would also filter out the payments.
v
If
update
always requires success, why is it a parameter?
And if you need it for whatever reason, just do not give
result
but simply hard-coded success, as you filter before that only success payments are left
p
ApiResult.Success carries the responseData, which is needed for the update.
That's can't be seen in the code snippet, sorry about that.
v
Ah, I see
Then cast it?
result as Success
p
How to do that in the filter method without losing the corresponding payment?
I could make payment a property of Result, but that wouldn't be the cleanest solution.
Well, the last mapping step in that workflow only logs the output, so I just use a guard clause inside update():
if (result !is ApiResult.Success) return
m
Hopefully you meant return@map there
👍 1
v
I don't understand what you mean Philipp, what is wrong with my suggestion?
Copy code
.map { (payment, requestModel) -> steps.performRequest(payment, requestModel) 
.filter { (_, result) -> result is ApiResult.Success }
.map { (payment, result) -> steps.update(payment, result as ApiResult.Success) }
AS you filtered for only the pairs that have success there, it should always succeed properly
👍 3
p
No, you're completely right Björn! I was just so focused on the filter method that I didn't even think about using it as input parameter to update. 😄
👌 1
Thanks a lot guys!
a
.mapNotNull { it as? FooBar }
is usually nice too
v
How would that help here?
Can you give the full example?