Wednesday, February 3, 2010

Chaining Options with orElse

A simple but handy use for Option is to select the first valid option from a selection of possible choices. Sound vague? Well it is because it can be used in many different situations. The one presented here is: the program needs a directory that can be set by the user either as a system variable, and environment variable or the default value. The java code is a nightmare of if (xxx == null) statements. The Scala code is beautiful.
  1. scala> val propsTemplates = Option(System getProperty "MVN_CREATOR_TEMPLATES")
  2. propsTemplates: Option[java.lang.String] = None
  3. scala> val envTemplates = Option(System getenv "MVN_CREATOR_TEMPLATES")
  4. envTemplates: Option[java.lang.String] = None
  5. scala> val defaultHome = Some(System getProperty "user.home")
  6. defaultHome: Some[java.lang.String] = Some(/Users/jeichar)
  7. /* 
  8. chain the different options together in order of priority and get the value
  9. I am taking a small liberty here because I am assuming that user.home is always available
  10. */
  11. scala> propsTemplates.orElse(envTemplates).orElse(defaultHome).get
  12. res0: java.lang.String = /Users/jeichar
  13. // alternative form:
  14. scala> propsTemplates orElse envTemplates orElse defaultHome get
  15. res1: java.lang.String = /Users/jeichar

2 comments:

  1. It's also nice to drop the periods and parens in this case.

    val templates = propsTemplates orElse envTemplates orElse defaultHome get

    ReplyDelete
  2. thanks I have added this to the post

    ReplyDelete