Can you store a variable inside a if-clause?

后端 未结 6 1614
不思量自难忘°
不思量自难忘° 2021-01-01 16:21

I\'m kinda waiting for a \'no\' answer on this question.

I was interested if you can save a variable at the same time when you checking it in an if-clause.

6条回答
  •  情歌与酒
    2021-01-01 16:41

    if you want to limit the scope of Bar bar I'd add { and } around the code that Michael posted.

    void foo()
    {
        // some code ...
    
        // this block limits the scope of "Bar bar" so that the rest of the method cannot see 
        // it.
        {
            Bar bar;
            if(foo!=null && (bar = foo.getBar())!=null){
                System.out.println("Success: " + bar);
            } else {
                System.out.println("Failiure.");
            }
        }
    }
    

    You might also want to check into the null object pattern if it makes sense. I personally try to avoid things being null if I can... really think about if you want null to be allowed or not.

提交回复
热议问题