Switch case with objects

In AS3 the following case works like a charm (btnPrev and btnNext are the buttons I touch):

switch (touch.target) {
	case btnPrev:{
		prevPage();
	}
	case btnNext:{
		nextPage();
	}
}

But in Haxe I have to change it to:

switch (touch.target) {
	case _ if (touch.target == btnPrev):{
		prevPage();
	}
	case _ if(touch.target == btnNext):{
		nextPage();
	}
}

Is this a proper way to compare objects?

I believe Haxe was developed with the idea that switch statements should be used for enums and direct primitives like strings, integers, etc. The design scheme isn’t nice to checking conditional booleans like this.

In this case, the proper way to compare objects is just if-else statements.

if ( touch.target == btnPrev ) {
     prevPage();
}
else if ( touch.target == btnNext ) {
    nextPage();
}

(FYI, Your AS3 code is similar to what one of my old bosses would do for data validation in a Flash game. He’d check against function calls in switch statements against the value “true”; if the data a function was inspecting was fine, the function would return false and go to the next case/function. If there was a problem with the data, the function would return true and trigger the code inside the case, which was usually some kind of error message.)

I’ve converted many Flash AS3 projects to HTML5 using OpenFl and Haxe and ran into the same problem. My solution was to name all my objects and then use the name in the switch statement. In your case switch (touch.target.name). Hope that helps.

1 Like