views:

883

answers:

4

I ran across the following code in Ely Greenfield's SuperImage from his Book component - I understand loader.load() but what does the rest of do?

loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));

It looks like some kind of crazy inline if statement but still, I'm a little preplexed. And if it is an if statement - is this way better than a regular if statement?

A: 

this is using the ternary ?: operator. the first part is the condition, between the ? and : is what to return if the condition is true. after the : is what to return if the condition is false.

a simpler example

String str = null;
int x = (str != null) ? str.length() : 0;

would be the same as

String str = null;
int x;
if (str != null)
  x = str.length()
else
  x = 0;
Matt
+1  A: 

Basically what it says is: if newsource is a type of URLRequest, then pass the newSource variable into the load method, if its not a type of URLReuqest, create a new URLRequest and pass that into the load method.

The basic syntax is: (condition) ? (code to execute if true) : (code to execute if false)

Jason Miesionczek
Awesome thank you - that makes sense now...
onekidney
+11  A: 

? is called the 'ternary operator' and it's basic use is:

(expression) ? (evaluate to this if expression is true) : (evaluate to this otherwise);

In this case, if newSource is a URLRequest, loader.load will be passed newSource directly, otherwise it will be passed a new URLRequest built from newSource.

The ternary operator is frequently used as a more concise form of if statement as it allows ifs to be inlined. The corresponding code in this case would be:

if (newSource is URLRequest)
   loader.load(newSource);
else
   loader.load(new URLRequest(newSource));
workmad3
A: 

Hi,

Basically what this means, as far as im aware of, is its asking wheter that variable newSource's class is String or URLRequest like workmad and jason explained. If its an URLRequest it will run loader.load(newSource:URLRequest). If its not an URLRequest it means automatically that it is a String (in other words the url). And in that case it will run loader.load(new URLrequest(newSource:String).

The complete code could look something like this:

function myFunction(newSource:Object):SomeClass {
var loader:URLLoader = new URLLoader();
loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));
}

Regards,

Filipe A.