You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Use the `flatMap` method with a closure that returns an optional value
But `f` is not "a closure that returns an Optional value". It returns an Int, not an Optional<Int>. I would have thought we'd have to call `map`, not `flatMap`.
Basically what's going on here is that the docs are wrong, or at least very misleading. The docs seem to say that the distinction is between what kind of closure they take: one that produces an Optional, or one that does not. But that is quite false. They both accept either kind of closure. All of these expression compile just fine:
Okay, so what's the actual difference? It's what `flatMap` does just in case the closure does produce an Optional: it unwraps it, thus preventing a doubly-wrapped Optional:
This is one of the reasons flatMap got renamed to compactMap.
What's going on here is that values implicitly convert to optionals. That's it. That means that if I have a closure that returns a value of type T, it can convert to a closure that returns a value of type T?. There's nothing special about using compactMap here; it'll just immediately unpack the value. I guess that could go in the docs for compactMap if it isn't there already?
Additional Detail from JIRA
md5: 2f8e29b8782cc896afe928e50fa3ad9e
Issue Description:
This compiles:
Why? The declaration is:
And the docs / comment say:
But `f` is not "a closure that returns an Optional value". It returns an Int, not an Optional<Int>. I would have thought we'd have to call `map`, not `flatMap`.
Basically what's going on here is that the docs are wrong, or at least very misleading. The docs seem to say that the distinction is between what kind of closure they take: one that produces an Optional, or one that does not. But that is quite false. They both accept either kind of closure. All of these expression compile just fine:
Okay, so what's the actual difference? It's what `flatMap` does just in case the closure does produce an Optional: it unwraps it, thus preventing a doubly-wrapped Optional:
Well, the docs should say that — and they don't.
The text was updated successfully, but these errors were encountered: