Question

I understand the concept of None I also understand how nice it is to have MyObj and also MyEmptyObj but i cant figure out when its better to use None instead of MyEmptyObj and when I should be using MyEmptyObj instead of None. Also I tend not to like to see methods that return Option[MyObj] it clutters my code I prefer to return MyObj and then seamlessly call its methods such as MyObj.toJson and thus MyEmptyObj.toJson will know to represent itself rather than having case None: return some empty json what do you think about this whole subject? To the other side I can say that None goes very well with flatMap etc, so which to choose?

when to None

and when to Empty?

Was it helpful?

Solution

None is great when you have no default value, but if you have a default, by all means use it.

As a very simple example, if you wanted to define a function called amountOwed, you could do this:

def amountOwed(bill: Int, alreadyPaid: Option[Int]): Option[Int] = {
  val owed = bill - alreadyPaid.getOrElse(0)
  if(owed == 0) None // nothing to pay!
  else Some(owed)
}

But that's much more complex (and annoying) than it needs to be, since 0 makes perfect sense as both a "haven't paid anything" and "don't owe anything":

def amountOwed(bill: Int, alreadyPaid: Int): Int = {
  bill - alreadyPaid
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top