Using OR outside an if statement

Hi,

I am converting a project from AS3 to OpenFL. One problem I found is that I often use the OR operator to decide what to return from a function. I have looked around, but could not find an answer.

Here is an example on how I use it:

public function getComponentByID(id:String, shallowSearch:Bool = false):Component{

    return getHotspotByID(id, shallowSearch) ||
    getButtonByID(id, shallowSearch) ||
    getCableByID(id, shallowSearch)  ||
    getSocketByID(id, shallowSearch) ||
    getLightByID(id, shallowSearch);
}

Is this possible to do in a similar way? Or do I have to come up with a different structure?
Thanks in advance!

In haxe the || operator is for booleans and even with operator overloading you can’t change the return type.
So I guess you’ll have to do that in a slightly different way.

You are going to have to check for null

Here are a couple ideas:

public function getComponentByID(id:String, shallowSearch:Bool = false):Component{
	
	var component = null;
	
	if ((component = getHotspotByID(id, shallowSearch)) != null) return component;
	if ((component = getButtonByID(id, shallowSearch)) != null) return component;
	if ((component = getCableByID(id, shallowSearch)) != null) return component;
	if ((component = getSocketByID(id, shallowSearch)) != null) return component;
	if ((component = getLightByID(id, shallowSearch)) != null) return component;
	
	return component;
	
}
public function getComponentByID(id:String, shallowSearch:Bool = false):Component{
	
	var component = null;
	
	for (i in 0...5) {
		
		component = switch (i) {
			
			case 0: getHotspotByID(id, shallowSearch);
			case 1: getButtonByID(id, shallowSearch);
			case 2: getCableByID(id, shallowSearch);
			case 3: getSocketByID(id, shallowSearch);
			default: getLightByID(id, shallowSearch);
			
		}
		
		if (component != null) break;
		
	}
	
	return component;
	
}

Here’s a macro, if you’d prefer. It’s easier to use than Joshua’s suggestions, and the resulting code is slightly more efficient.

Thanks a lot for your suggestions, I really appreciate it!