Error using a method call as a default function argument
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>" );
}
Comments