In ColdFusion, a closure can take two forms: the multi-line syntax in which the body of the function is wrapped in traditional braces ({ body }); and the one-line syntax in which the body-braces are omitted and the one-line expression is processed with an implicit return statement. The one-line syntax can be really handy for simple mappers and filters; but, it gets complicated when the one thing you want to return is a struct literal.
In ColdFusion, a struct literal is primarily demarcated by open-and-close braces. Which is exactly what a function body uses. So if you try to write a one-line closure that returns a struct:
fn = () => {};
... it's impossible for the ColdFusion compiler to know if those empty braces - {} - represent a struct literal? Or, a function body? As of today, all of the CFML engines (Adobe, Lucee, Boxlang) treat this as a function body that returns null.
One option is to use a different struct literal syntax. Instead of creating a standard struct, you can use square brackets to create an ordered struct:
fn = () => [:];
Now, without the curly braces, the CFML parser can clearly see that this is a one-line closure that returns a struct literal.
The other option is to use an explicit return statement. This one surprised me. Meaning, I didn't know you could use a return statement in a one-line closure function. But, you can — and it works in all the CFML engines:
fn = () => return {};
I don't always use one-line closures in ColdFusion because they walk a delicate line between simplicity and readability. But sometimes, they are exactly the right tool for the job; and it's nice to know that if we need to return a struct literal, we have a few options that don't mandate dropping back into the multi-line syntax.
Reader Comments
As a quick aside, this explicit
returnin an one-line closure does not work in JavaScript. It will throw a parsing error.Post A Comment — ❤️ I'd Love To Hear From You! ❤️
Post a Comment →