If I'm writing Scala functions and have to check for nulls in situations where I can't avoid it (say, working with Spark UDFs and some legacy Java types), is it better to turn things into Option
or to write conditional branches?
Example:
case class Foo (
bars: Seq[Bar]
)
case class Bar(s: String)
def findBarWithConditionals(foo: Foo, barToFind: String): Option[Bar] = {
if (foo == null || foo.bars == null) {
None
} else {
foo.bars.find(_.s == barToFind)
}
}
def findBarWithOptions(foo: Foo, barToFind: String): Option[Bar] = {
Option(foo).flatMap(f => Option(f.bars).map(_.find(_.s == barToFind)))
}
Is there a rule of thumb of how to weigh readability vs. maintaining functional programming principles? Or is this purely opinion?
Option
to start with so you didn't have to fake null checks.