Closures in ColdFusion: Structures/Collections

Railo 4 supports closures (a.k.a. anonymous functions) in ColdFusion.

I’ve been playing with the different ways of using them in the various apps I am building at Straker Translations.

Today there was a need to loop over the keys of a structure (a.k.a. associative arrays) and add the value of all the keys.

The usual idiom of regular ColdFusion code would be to use <cfloop> to go over all the keys and do the addition.

With Railo closures it is much simpler. Here is the code:

<cfscript>
// this is the collection we want to loop over and add all the keys
numbers = { "num1" : 3, "num2" : 4}
// setup a variable to hold the sum of the value of all the keys
sum = 0
// closure magic
numbers.each( function(k,v){
return sum+= v;
})
</cfscript>

It is simple and elegant. Makes the code much more succinct and powerful.

Leave a Reply

Your email address will not be published. Required fields are marked *