Ternary and Null Coalescing

These examples would probably elicit a comment if they came up during a code review, mostly because of the null. While this isn’t really the main point, I thought I might provide a quick couple of alternatives that are a bit more idomatic:

findPerson().fold("No person found")(_.name)
findPerson().map(_.name).getOrElse("No person found")

No real point in messing with null if you’ve already got an Option ¯\_(ツ)_/¯

4 Likes