I have a ColdFusion function "foo" which takes three args, and the second two are optional:
<cffunction name="foo" access="public" returntype="any">
<cfargument name="arg1" type="any" required="true" />
<cfargument name="arg2" type="any" required="false" default="arg2" />
<cfargument name="arg3" type="any" required="false" default="arg3" />
...
<cfreturn whatever />
</cffunction>
I want to call foo, passing in arg1 and arg3, but leaving out arg2. I know that this is possible if I call the function using cfinvoke
, but that syntax is really verbose and complicated. I have tried these two approaches, neither works:
<cfset somevar=foo(1, arg3=3) /> <!--- gives syntax error --->
<cfset somevar=foo(1, arg3:3) /> <!--- gives syntax error --->
You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.
So, it is optional during a call. If a value is provided, it will overwrite the default value. Any number of arguments in a function can have a default value.
Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.
By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.
You have to use named arguments throughout. You can't mix named and positional arguments as you can in some other languages.
<cfset somevar = foo(arg1=1, arg3=3) />
Or.. you can use ArgumentCollection
In CF9 or above...
<cfset somevar = foo(argumentCollection={arg1=1, arg3=3})>
In CF8 or above...
<cfset args = {arg1=1, arg3=3}>
<cfset somevar = foo(argumentCollection=args)>
If CF7 or below...
<cfset args = structNew()>
<cfset args.arg1 = 1>
<cfset args.arg3 = 3>
<cfset somevar = foo(argumentCollection=args)>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With