Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does arrayAppend return true and listAppend return the list?

Tags:

coldfusion

In ColdFusion, the arrayAppend() function takes an array and an item to be appended. It modifies the array that was passed in and returns true if successful.

The listAppend() function, however, takes a list and an item to be appended, and returns a new list with the item appended. It doesn't modify the list that was passed in.

Why do these functions operate in two different ways? I'm always turning to the documentation to remember the return value of each.

like image 587
stomcavage Avatar asked Jul 16 '09 16:07

stomcavage


2 Answers

This is because there is no "List" data type in ColdFusion.

A "List" is a delimited string, simple as that. It is comma-delimited by default, but you can choose the delimiter. "ListAppend()" is a string concatenation operation, and as such it returns the result of its work just like "string1 & string2" would.

The only thing that "ListAppend()" does for you is: It takes care of the delimiter handling, preventing needless double delimiters - something that "string1 & string2" cannot do.

An array is a real data type and (in contrast to a string) can be modified in-place. This is what ArrayAppend() does.

like image 171
Tomalak Avatar answered Oct 01 '22 04:10

Tomalak


To understand why this happens you need to know a little bit about how Strings work in Java because the underlying implementation of a list in ColdFusion is a java.lang.String.

<cfset list = "a,b,c"/>
<cfoutput>#list.getClass()#</cfoutput>

In Java, Strings are immutable and have no methods to modify the contents of a String. If you did the following in Java, you would be creating a new instance of a String and assigning it to s for each statement:

String s = "abc";
s = "def";
s = s.concat("ghi");

Using the listAppend() method in ColdFusion is creating a new instance of a String under the hood and returning it, thus the need to do something like this whenever you append values to a list.

<cfset list = "a,b,c"/>
<cfset list = listAppend(list,'d')/>
<cfoutput>#list#</cfoutput>

However, when you modify an array with arrayAppend(), you are directly modifying the array, thus there is no need to reassign the value to itself again like you need to with listAppend().

like image 38
Jayson Avatar answered Oct 01 '22 05:10

Jayson