Pages

Tuesday, February 21, 2012

Scala saves you lines

Very brief post about Scala programming

Few days ago I played a bit with Scala's fold operations.

I had a list containing rules that all needed to be completed to continue.

Because I have a long history with Java, the first version:
def areRulesCompleted(ruleList:List[Rule]):Boolean= {
var isCompleted:Boolean = true
ruleList.foreach(rule =>{
if (!rule.isCompleted) isCompleted = false
})
return isCompleted
}

As you can see there's plenty of rows and it's not very functional. Then with foldLeft
ruleList.foldLeft(true)((resolvedValue,rule)=>(resolvedValue && rule.isCompleted))
Better! But we can do it even simpler way
ruleList.foldLeft(true)(_ && _.isCompleted)

so combining this with the method declaration:
def areRulesCompleted(ruleList:List[Rule]) = ruleList.foldLeft(true)(_ && _.isCompleted)
Here's even shorter version (short-circuit) by: Ilkka.
def areRulesCompleted(rules: List[Rule]) = !rules.exists(!_.isCompleted)
I also checked that foldLeft is short-circuiting but foldRight is not.