I have a function that perform a calc but i'm using a var to receive the value of a recursive function and i would like to avoid mutable variables.
def scoreNode(node:Option[Tree], score:Double = 0, depth:Int = 0):Double = {
node.map(n => {
var points = score
n.children.filter(n => n.valid == Some(true)).foreach(h => {
points = scoreNode(Some(h), 10, depth+1)
})
points
}).getOrElse(score)
}
How can i rewrite this piece of code without a mutable variable? I've tried
Optionand immediatelymapon it, that your code gets easier to manage if you change the type signature to accept the non-optional type andmapat the call site. That would remove some of the noise here and make it easier for you to see the behavior alonescoreNode(node: Option[Tree], ...) = node.map(...)instead writescoreNode(node: Tree, ...) = ...and call it bymaybeNode.map(scoreNode).getOrElse(defaultScore)