Note that there are some explanatory texts on larger screens.

plurals
  1. POConfiguration data in Scala -- should I use the Reader monad?
    text
    copied!<p>How do I create a properly functional configurable object in Scala? I have watched Tony Morris' video on the <code>Reader</code> monad and I'm still unable to connect the dots. </p> <p>I have a hard-coded list of <code>Client</code> objects: </p> <pre><code>class Client(name : String, age : Int){ /* etc */} object Client{ //Horrible! val clients = List(Client("Bob", 20), Client("Cindy", 30)) } </code></pre> <p>I want <code>Client.clients</code> to be determined at runtime, with the flexibility of either reading it from a properties file or from a database. In the Java world I'd define an interface, implement the two types of source, and use DI to assign a class variable:</p> <pre><code>trait ConfigSource { def clients : List[Client] } object ConfigFileSource extends ConfigSource { override def clients = buildClientsFromProperties(Properties("clients.properties")) //...etc, read properties files } object DatabaseSource extends ConfigSource { /* etc */ } object Client { @Resource("configuration_source") private var config : ConfigSource = _ //Inject it at runtime val clients = config.clients } </code></pre> <p>This seems like a pretty clean solution to me (not a lot of code, clear intent), but that <code>var</code> <em>does</em> jump out (OTOH, it doesn't seem to me <em>really</em> troublesome, since I know it <em>will</em> be injected once-and-only-once). </p> <p>What would the <code>Reader</code> monad look like in this situation and, explain it to me like I'm 5, what are its advantages? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload