Is there a simple way of defaulting out of bounds in nested Seqs in Scala?

Take the following code from the question:

myVector.lift(i) map (_.lift(j) map f getOrElse false) getOrElse false

This can be rewritten as follows:

myVector.lift(i).flatMap(_.lift(j)).fold(false)(f)

Or, before fold was introduced in Scala 2.10:

myVector.lift(i).flatMap(_.lift(j)).map(f).getOrElse(false)

The key idea is to defer unwrapping (or mapping) the Option for as long as possible. This approach will generalize quite naturally to more than two dimensions.

This is pretty close to equivalent to the for-comprehension in your answer (assuming you meant to include lift in there), but once you have to wrap the comprehension in parentheses I personally tend to find the desugared version clearer.

Tags:

Scala