https://kotlinlang.org logo
#functional
Title
# functional
b

bbaldino

12/09/2021, 8:52 PM
Hope this is the right channel to ask this. I’m trying to figure out the correct way to “flatten” nested
Result
types. I have a method like this:
Copy code
fun one(): Result<SomeType> {
    return two()
        .map { someOtherType ->
            three(someOtherType)
                .map { someType -> 
                    doSomethingWithSomeType(someType)
                    someType
}

fun two(): Result<SomeOtherType> { ... }
fun three(someOtherType: SomeOtherType): Result<SomeOtherOtherType> { ... }
the compiler complains that I’m returning
Result<Result<SomeType>>
instead of
Result<SomeType>
, which I think I get…I just can’t remember the right way combination of `map`/`fold`/something else to “flatten” the result?
r

Richard Gomez

12/09/2021, 9:08 PM
I think you want is
flatMap
. Think of flatmap as "and then", whereas map is "transform value".
b

bbaldino

12/09/2021, 9:09 PM
That was my first thought as well, but there doesn’t seem to be a
flatMap
defined on
Result
?
I generally avoid the built-in Result type because it lacks a lot of features, and prefer something like https://github.com/michaelbull/kotlin-result/ instead
b

bbaldino

12/09/2021, 9:11 PM
Ah ok. Yes I was all excited to hear
Result
as a return had been stabilized, but since then I think every discussion I’ve read about it has had at least one person pointing to that lib 🙂
Does look like a nice API…I think I’ll give it a shot. Thanks!