Note that there are some explanatory texts on larger screens.

plurals
  1. POAlternative to doing lots of calculations in constructor - scala
    primarykey
    data
    text
    <p>I'm learning scala for a new project, aiming for immutability and functional style wherever possible. </p> <p>One of the objects I'm creating takes a number of inputs in its constructor, then repeatedly applies a large number of calculations to generate the relevant outputs, which are stored as fields on the object.</p> <p>While the calculations are performed and their results added to a mutable <code>ListBuffer</code> internally, everything else about the object is immutable - once created you can't change any of the input values and running the calculations again would obviously produce the same result.</p> <p>However, it doesn't seem right to me to have so many calculations in the constructor. The only way around it I can see is to have the calculated values be <code>var</code>s and provide a <code>run</code> method which performs the calculations - but then this method could be called multiple times, which would be pointless. </p> <p>Is it actually OK style to do a lot in a scala constructor? There's no calls to the DB for example, just internal calculations. Or is there some pattern for this?</p> <p>Here's the basic idea in very very simple form:</p> <pre><code>class Foo(val x:Int, val y:Int, calculations:List[Calculation]) { val xHistory = new collection.mutable.ListBuffer[Int]() val yHistory = new collection.mutable.ListBuffer[Int]() calculations.map { calc =&gt; calc.perform(this) }.foreach { result =&gt; xHistory += result.x yHistory += result.y } } </code></pre> <p>Basically I want the inputs wrapped in a handy instance of a <code>Foo</code> object so I can pass it to the various calculation strategies (each of which may need a different combination of inputs).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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