Menu

As simple as possible, as complex as necessary

Error using a method call as a default function argument

5 September 2013

When creating a method within a ColdFusion Component it's not uncommon to set the default value of an argument to be the result of an existing method in that CFC. For example:

Cat.cfc

component
{
	function init()
	{
		return this;
	}

	numeric function loudness()
	{
		return 1;
	}

	void function purr( numeric loudness=loudness() )
	{
		WriteOutput( "<p style=""font-size:#arguments.loudness#em"">Purrr</p>" );
	}
}

However trying to instantiate the above CFC on CF9.0.1 results in an error:

java.lang.UnsupportedOperationException: can't load a null

Can you spot why?

Same name blame

Yes, it's because the argument and function are both called: loudness.

In this case the choice of name for the function is clearly rather poor and we could fix things by simply renaming the loudness() method as defaultLoudness().

But in a more complex CFC I was working on earlier, the naming was justified and I didn't want to use contrived names for either just to make it work.

Fortunately it's possible to avoid the problem without renaming by scoping the method with either this. or variables.

void function purr( numeric loudness=this.loudness() )
{
	WriteOutput( "<p style=""font-size:#arguments.loudness#em"">Purrr</p>" );
}

Posted on . Updated

Comments

  • Formatting comments: See this list of formatting tags you can use in your comments.
  • Want to paste code? Enclose within <pre><code> tags for syntax higlighting and better formatting and if possible use script. If your code includes "self-closing" tags, such as <cfargument>, you must add an explicit closing tag, otherwise it is likely to be mangled by the Disqus parser.
Back to the top