Skip to main content
Ben Nadel at cf.Objective() 2013 (Bloomington, MN) with: Jason Dean
Ben Nadel at cf.Objective() 2013 (Bloomington, MN) with: Jason Dean

Returning A Struct From A One-Line Closure In ColdFusion

By
Published in — Comments (1)

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.

Want to use code from this post? Check out the license.

Reader Comments

Post A Comment — I'd Love To Hear From You!

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
— Ben Nadel
Managed ColdFusion hosting services provided by:
xByte Cloud Logo