How to code this configuration logic in Scala?
-
20-06-2021 - |
Question
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?
Solution
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).
OTHER TIPS
List(getFromArgs _, getFromSystemProperties _, getFromUserConfigFile _).map{func=>
Option(func("MyParam"))
}.reduce(_ orElse _).getOrElse(sys.error("No MyParam"))
Checkout scala Option cheatsheet. Option is powerful.
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/
(
Option(getFromArgs("MyParam")) orElse
Option(getFromSystemProperties("MyParam")) orElse
Option(getFromUserConfigFile("MyParam")) getOrElse
error("No MyParam")
)