How do you rewrite this Scala class with variable fields in a more functional style? -
class myclass { var myfield = list.empty[double] var mysecondfield = list.empty[double] def mymethod = { // code heavy computation myfield = mycomputationoutput mysecondfield = mysecondcomputationoutput } }
i avoid saving state in myclass, seems convenient store computed values during mymethod call.
what design alternatives?
if caching results of heavy computations, use memoize pattern. compute result first time , return if parameters same:
class myclass { var myfield = option[list[double]] = none var mysecondfield = option[list[double]] = none def mymethod = { if ( ! myfield.isdefined ) { myfield = some(mycomputationoutput) } if ( ! mysecondfield.isdefined ) { mysecondfield = some(mysecondcomputationoutput) } } }
if values never change, consider computing them first time referenced, using lazy evaluation:
class myclass { lazy val myfield = mycomputationoutput lazy val mysecondfield = mysecondcomputationoutput }
another approach consider myclass
2 classes, corresponding 2 phases, i.e., before , after computation done. then, mutability global state, rather amalgam of states of 2 variables.
Comments
Post a Comment