Friday, February 12, 2010

Option is Iterable

Event though the method exists doesn't exist on the Option class, there is an implicit conversion from Option to Iterable. Exists is a useful method when processing the value contained within option.

def isBefore (a: Option[Int], b: Option[Int]): Boolean = {
  a.exists(x => b.exists(x < _))
}

println("5 is before 3 :" + isBefore(Some(5), Some(3)))
println("3 is before 5 :" + isBefore(Some(3), Some(5)))
println("5 is before none: " + isBefore(Some(5), None))
println("3 is before none: " + isBefore(None, Some(3)))

Produces
5 is before 3 :false
3 is before 5 :true
5 is before none: false
3 is before none: false

No comments: