Raman Mishra
Raman Mishra

Reputation: 2686

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.

Upvotes: 1

Views: 676

Answers (2)

Andrey Tyukin
Andrey Tyukin

Reputation: 44908

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.

Upvotes: 5

Karl Bielefeldt
Karl Bielefeldt

Reputation: 48998

The size method is added because Options are implicitly converted to an Iterable. Iterable provides a ton of useful methods without having to be specifically reimplemented for Options. By reusing that code, Options gain consistency with all other containers, and are much more reusable themselves.

In other words, it lets you pass an Option into a function expecting an Iterable, where that function only knows about methods like size and not Option-specific methods like isDefined.

Really, isDefined is the method you don't strictly need, because it only makes sense for the narrow Option type. It's just there to provide a semantically nicer name than size or isEmpty.

Upvotes: 3

Related Questions