• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 3. Function Return Typing

Chapter 3. Function Return Typing

DO OR DIE

  • Set what kind of information a function returns.

  • Really, just like strong typing.

Function return typing is a lot like strong typing. It looks like this:

function wardrobeMalfunction(numSnaps):Number
{
    // bunch of code here
    return numBoobsDisplay;
}

All this says is that numBoobsDisplay had better be a number, or Flash will throw an error. For example,

function wardrobeMalfunction(numSnaps):Number
{
    var revealed:String = "Go Justin go";
    return revealed;
}
wardrobeMalfunction(5);

results in an error because we tried to return a string when the function demands that a number be returned.

Here's another example that returns an array.

origArray = ["the fonz","Bumblecakes","sea","DeeDee","Eek","fark","ghost","ha-cha-cha","eye","Homer Jay"]

function shuffleArray(userArray):Array
{
    var tempArray:Array = new Array();
    var shuffledArray:Array = new Array();

    // create a copy
    for (i=0; i<userArray.length; i++) tempArray[i] = userArray[i];

    // create the shuffled array
    while (tempArray.length > 0) {
          randomElement = int(Math.random()*tempArray.length);
          shuffledArray.push(tempArray[randomElement]);
          tempArray.splice(randomElement,1);
    }
    return shuffledArray;
}

shuffled = shuffleArray(origArray);
trace (shuffled);


					  

FAQ

Tom[*] Asks Why

As with strong typing, the idea is to force you to follow your own rules. You should know what your functions are returning, and you should know if they're doing something different. As with strong typing, it doesn't do anything but alert you to potential bugs in your code—and it builds muscles. Gives you a cute butt. So do it.


[*] I have a friend named Tom who recently gave computer programming the one-finger salute and returned to his musical roots. But while he was learning to program, he complained about computer books. “They tell you how to do something, but not when to do it!” So, in an effort to avoid the aforementioned salute, I'll try to add a little context to the code and let you know when to actually use a certain function or method.

On my Web site (www.wire-man.com/garage), you can download the code, which contains comments that talk a bit more about the code.

Try changing the bolded Array to Number, and see what happens. (That's right. The moon falls out of orbit.)

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 17: The expression returned must match the function's return type.
          return shuffledArray;

Total ActionScript Errors: 1       Reported Errors: 1


					  

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint