flatMap
See original GitHub issueI can’t see a flatMap function or its equivalent which is typical for monads. It should work like Haskell’s >>=.
My suggested implementation:
infix inline fun <V, E, U> Result<V, E>.flatMap(transform: (V) -> Result<U, E>) : Result<U, E> {
return when (this) {
is Ok -> transform(value)
is Err -> this
}
}
Also flatMapError function could be implemented in simillar way. If you like the idea, I will implement them along with unit tests and create a pull request.
Thanks!
Issue Analytics
- State:
- Created 6 years ago
- Comments:11 (8 by maintainers)
Top Results From Across the Web
Array.prototype.flatMap() - JavaScript - MDN Web Docs
The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening...
Read more >What's the difference between map() and flatMap() methods in ...
The flatMap method lets you replace each value of a stream with another stream and then joins all the generated streams into a...
Read more >The Difference Between map() and flatMap() - Baeldung
The map() method wraps the underlying sequence in a Stream instance, whereas the flatMap() method allows avoiding nested Stream<Stream<R>> ...
Read more >JavaScript Array flatMap() By Practical Examples
The flatMap() method first maps each element in an array using a mapping function and then flattens the results into a new array....
Read more >A Smarter JavaScript Mapper: array.flatMap() - Dmitri Pavlutin
array.flatMap() method is the way to go if you want to map an array to a new array, but also have control over...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

You mention the extension function for Kotlin’s
Mapclass. However there is also a version forIterablewith signaturefun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R>. As you can see this is really similar to yourandThenby parameters and return type. Both functions are defined for someMonad<T>take function(T) -> Monad<R>and returnMonad<R>, that’s why this name seems reasonable for me.Also in this alternative library that operation is called
flatMap.Of course using Elm’s convention also makes sense.
Well, there also is a
flatMapmethod in Java’sOptionaland similaryflatMapin Scala’sOption. They are equivalent to yourandThenas much as they can be!I agree that the name itself is confusing, however it somehow shows a relationship with
map. Still I believe this is a common name for this type of operation in Java’s world.