Create a new variable and check if it's null in one if

Nuno Mendes :

Can I do something like this?

if(variable = class.GetVariable() != null){
    variable.doSomething()
}

As I said in the comments I'm doing this with a HttpSession, so my goal is to check if there is a parameter in the session with a specific name and if it is do something.

Michael Berry :

You can, so long as variable has already been defined and you add additional brackets:

Foo variable;
if ((variable = GetVariable()) != null) {
    variable.doSomething();
}

You tend not to see this pattern often as it's not the most readable, but it is often seen when reading from a BufferedReader line by line (as it provides a convenient, quick way to read lines until there aren't any):

String line;
while((line=reader.readLine())!=null) {
    //Process each line
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307794&siteId=1