How does Option act like a collection, when it isn't one?
Asked Answered
T

1

1

The accepted answer to "How to convert a Some(“ ”) to None in one-line?" took the form:

def convert(x: Option[String]) : Option[String] = 
    x.map(_.trim()).filterNot(_.isEmpty())

My problem is that I can't figure out how to find by what means the collection returned by filterNot is converted to an Option. I looked at the Scaladoc for Option constructors, Option Object, Predef, Seq, and Seq Object. I figure there's probably an implicit somewhere, but how does one go about finding it?

Talented answered 6/3, 2012 at 14:30 Comment(3)
It doesn't act like a collection, it acts like a monad. As do collections.Unwarrantable
@LuigiPlinge: Something with foreach and iterator is a collection, at least by my duck test - these methods are not intrinsic to monads, are they? In what way are you saying that it does not act as a collection - or aren't you?Talented
In this example you're saying it's like a collection because it has map and filter methods. But these are monad operations (along with flatMap). Sure, you can think of Options as like collections (there's even an implicit conversion to List) but it's irrelevant for this question. It's like saying Option is like a Foo because they both have a toString method.Unwarrantable
T
2

In scaladoc, you can click the "by inheritance" ordering button (it appears just above the methods description). This should help you finding the concrete implementation of a given method. The jump to that class and have a look to the source (the links to the source appears in the class/trait/object description).

In the case of Options, there are methods called map, filter, etc.

When an implicit value is required, you will notice, either an implicit clause in the argument list, or a context bound like [A: MyImplicit] in the parameters. Implicit are usually imported or declared in the companion object.

If you have a more specification question/example, please let me know.

Tomasine answered 6/3, 2012 at 14:35 Comment(5)
Ah! Sorry, I finally got it. I had assumed that Option would have some indicating trait or inheritance if it were itself a collection - once I saw that it was just a Product, I didn't even look at its own members, because I "knew" that map, et al wouldn't be there.Talented
The concrete implementations of a given method are always given below its description.Readability
@DanielC.Sobral Do you mean the definition class ?Tomasine
@DanielC.Sobral: They're only there if you actually bother to look at them ;-( - which I didn't (see earlier comment).Talented
@Tomasine Below the description of a method there's a list of classes/traits. The last one is the definition class/trait, and all the others are overrides, in the order of precedence (ie, the first class/trait contains the implementation that will actually be called).Readability

© 2022 - 2024 — McMap. All rights reserved.