你能在if子句中存储一个变量吗? [英] Can you store a variable inside a if-clause?

查看:128
本文介绍了你能在if子句中存储一个变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点等待这个问题的'不'答案。

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

我很感兴趣,如果你可以在检查时同时保存一个变量在if子句中。

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

假设我有这段代码。

if(foo!=null){
  if(foo.getBar()!=null){
    Bar bar = foo.getBar();
    System.out.println("Success: " + bar);
  } else {
    System.out.println("Failure.");
  }
} else {
  System.out.println("Failure.");
}

我现在处理失败 - 状态独立,即使结果是一样。我可以像这样把它们组合在一起:

I handling now to "failure" -states independently, even if the outcome is the same. I could get them together like this:

if(foo!=null && foo.getBar()!=null){
  Bar bar = foo.getBar();
  System.out.println("Success: " + bar);
} else {
  System.out.println("Failure.");
} 

已有更多更简洁的代码。如果foo为null,它将停在那里并且不会尝试foo.getBar(在if中)所以我不会得到NPE。我想要提升的最后一件事,以及主要问题:我是否真的两次打电话给foo.getBar()?如果getBar()将是一个非常繁重的操作,那么离开第二个相同的调用会很好。所以我想知道是否有可能做出类似的事情:

Much neater code already. if foo is null it will stop there and won't try foo.getBar (in the if) so I won't get a NPE. The last thing i would like to enhance, and the main question: Do I really gave to call on foo.getBar() twice? It would be nice to get away from the second identical call if getBar() would be a very heavy operation. So I am wondering if there is somehow possible to do something similiar to this:

if(foo!=null && (Bar bar = foo.getBar())!=null){
  Bar bar = foo.getBar();
  System.out.println("Success: " + bar);
} else {
  System.out.println("Failure.");
}

如果我愿意,我必须将其分解为两个不同的if要做

I would have to break it up to two different if's again if I would like to do

Bar bar = foo.getBar();
if (bar!=null) ...


推荐答案

这是你最接近的:

Bar bar;
if(foo!=null && (bar = foo.getBar())!=null){
  System.out.println("Success: " + bar);
} else {
  System.out.println("Failiure.");
}

这篇关于你能在if子句中存储一个变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆