Search code examples
scalafilterscala-option

Scala Option filter method doubts


I have been reading through Scala docs and while skimming through Option class I saw filter implementation that looks like this:

final def filter(p: A => Boolean): Option[A] = 
  if (isEmpty || p(this.get)) this else None

Why do we have to check whether our Option instance is empty? Wouldn't this result in None either way?


Solution

  • The || is short-circuiting, so checking isEmpty first ensures that get won't be called on an empty option (which would throw an exception).