The lowly switch statement and its attendant case statements is a basic element of most C-style languages. Still, I was surprised by it recently when it seemingly ate one of my functions. Read on to see how.

I’d like you to consider the following demo app:

public function foo()
{
	function f(): void
	{
	}
	for (var i:int = 0; i < 2; ++i)
	{
		switch (i)
		{
			case 0:
				function f2(): void
				{
				}
				printFunctions(f, f2);
				break;
			case 1:
			{
				function f3(): void
				{
				}
				printFunctions(f, f3);
				break;
			}
		}
	}
}
 
private function printFunctions(one:Function, two:Function): void
{
	trace("one: " + one + ", two: " + two);
}

The app simply runs a switch statement twice. Each time it goes into a different case. Both cases do the same thing: they call a simple function and pass two Function variables. Both cases pass the same function for the first argument but then differ on the second argument. The first case passes a dynamic function defined directly in the case. The second case passes a dynamic function created in a block in the case. Is there a difference? Let’s see:

one: function Function() {}, two: null
one: function Function() {}, two: function Function() {}

When I stumbled upon this error, I had essentially written the first case. Boy was I shocked to see a null! Since AS3 uses hoisting to essentially pull variables out to the function level, it would seem to me at first that it wouldn’t matter where the local function was defined. I could also see the function being invalid after the switch, but this is usage immediately after the function is defined. If the function isn’t valid there, where is it valid? Let’s try one more experiment by adding a third case:

case 2:
	function f4(): void
	{
	}
	log("f4: " + f4);
	break;

And the output:

f4: null

There you have it. The function you’ve just written is totally unusable. There were no compiler errors or warnings. To me, that calls for an error or at least a strongly-worded warning. Since you will get none from MXMLC, consider this article your unofficial warning. Beware the case statement!