scalamethodsfunctional-programmingmonadsscala-option

What is the possible use of (Monad) Option.size in scala


When we do Some(“some values”).size it returns 1. When we do None.size it returns 0. I was wondering what could be the possible use of the size method on an option.

val x = Some(1,2,3,4).size
println(x) // prints 1
val y = Some(List(“a”, ”b”, ”c”, ”d”))
println(y) //it also print 1

When we are going to have 1 for any kind of value inside Some and 0 for None. What is the use of this size method over Option.

One possible use I can think of is to know whether the option is defined in case of (Some) and size is 1 or not when None and size is 0.

But is doesn’t make sense because we already have isDefined to check that.


Solution

  • The size method does not have anything to do with the fact that Option is also a monad. The concept of a monad is quite general, it applies to a lot of things, and all those things will typically have many more methods that just unit and flatMap. Option has a size method because it is implicitly convertible via Option.option2iterable into an Iterable. This makes sense, because an Option is a collection with at most one element.

    I don't see any reason why isDefined should "make more sense" than size. None of those methods are strictly necessary. In fact, all methods on Option could be expressed in terms of fold only. For example, isDefined could be defined as

    def isDefined = fold(false){ _ => true }
    

    Likewise, size could also be defined through a fold:

    def size = fold(0){ _ => 1 }
    

    Does it now mean that we should throw away all methods except fold? No, not at all. "Rich interfaces" implemented as traits that provided tons of derived methods were probably the main reason why Scala's collections are so much more pleasant to use compared to, for example, Java's collections. By now, the difference has become smaller, because Java has also introduced default method implementations that do something similar, but this just shows once again that rich interfaces are inherently useful.