3

This is a follow-up to my previous question

Suppose I use the following logic (in quasi-Java) to get a configuration parameter MyParam :


String myParam = null

if ((myParam = getFromArgs("MyParam")) != null)
   return myParam

if ((myParam = getFromSystemProperties("MyParam")) != null)
   return myParam

if ((myParam = getFromUserConfigFile("MyParam")) != null)
   return myParam

... // and so on

if (myParam == null)
   error("No MyParam")

How to code this logic in Scala? Is Applicative applicable here?

1
  • 1
    The idea of monoids is probably more useful than applicatives here—xiefei's answer below takes advantage of the fact that Option's orElse is essentially the plus operation for what's sometimes called the "First" monoid instance for Option. Jul 11, 2012 at 15:48

4 Answers 4

8
List(getFromArgs _, getFromSystemProperties _, getFromUserConfigFile _).map{func=>
  Option(func("MyParam"))
}.reduce(_ orElse _).getOrElse(sys.error("No MyParam"))

Checkout scala Option cheatsheet. Option is powerful.

0
5

If your problem is only a matter of syntax, xiefei answer is exact.

If instead you are really looking for a flexible configuration I would suggest you warmly look to the Typesafe config project at : https://github.com/typesafehub/config/

3
(
  Option(getFromArgs("MyParam")) orElse
  Option(getFromSystemProperties("MyParam")) orElse
  Option(getFromUserConfigFile("MyParam")) getOrElse
  error("No MyParam")
)
2

As I noted in a comment above, you can use a "First" monoid instance for Option (really you only need a semigroup) to do this—for example, with Scalaz:

import scalaz._, Scalaz._

def fo[A](a: A) = Option(a).fst

val param = (
  fo(myParam) |+|
  fo(getFromArgs("MyParam")) |+|
  fo(getFromSystemProperties("MyParam")) |+|
  fo(getFromUserConfigFile("MyParam"))
) getOrElse sys.error("No Param")

It's not necessarily preferable to the orElse versions using the standard library, but it highlights the relevant abstraction (note also that this version is lazy—the getX calls won't happen if they aren't needed).

1
  • Thanks. Semigroup does look like a relevant abstraction. Now I wonder how this abstraction can actual help in practice in this (or similar) example.
    – Michael
    Jul 12, 2012 at 6:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.