I am learning scala for a new project, striving for immutability and functional style where possible.
One of the objects that I create accepts several inputs in its constructor, and then re-applies a large number of calculations to create the corresponding outputs, which are stored as fields on the object.
While the calculations are performed and their results are added to the mutable ListBuffer internally, everything else about the object is immutable - after creating you cannot change any of the input values and repeat the calculations, obviously the result.
However, it seems wrong to me that there are so many calculations in the constructor. The only way I can see is to have calculated var values and provide a run method that does the calculations, but then this method could be called multiple, which would be pointless.
Does OK style really do a lot in scala constructor? There are no calls to the database, for example, only internal calculations. Or is there some kind of template for this?
Here is the basic idea in a very simple way:
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 => calc.perform(this) }.foreach { result => xHistory += result.x yHistory += result.y } }
Basically, I need inputs wrapped in a convenient instance of the Foo object, so I can pass it to various calculation strategies (each of which may require a different combination of inputs).
Russell
source share