[英]Java 1.7 if statement on result of declaring and initialising a variable with scope of the if statement
Yarh- this is hard to explain. 是的-这很难解释。 Is it possible to so something like this: 是否有可能是这样的:
static String nullOrLastname(String name)
{
if(name.equals("jonas")) return "marshen";
return null;
}
if( (String lastname=nullOrLastname("jonas")) != null)
{
System.out.println(lastname);
}
This works, but is ugly etc. 这可行,但是很丑等。
for(String lastname = nullOrLastname("jonas");lastname !=null;lastname=null)
{
System.out.println(lastname);
}
Is there a better way? 有没有更好的办法? What is the name of what I want to do? 我想做什么的名字是什么? Did I use the correct words in the headline? 我在标题中使用了正确的单词吗?
I would do the following if you don't want scope leak. 如果您不希望范围泄漏,我将执行以下操作。
{
String lastname = nullOrLastname("jonas");
if (lastname != null)
System.out.println(lastname);
}
In Java 8 you would use an Optional and turn this into a one liner. 在Java 8中,您将使用Optional并将其变成一个内衬。
static Optional<String> nullOrLastname(String name) {
return Optional.ofNullable("jonas".equals(name) ? "marshen" : null);
}
public static void main(String[] args) {
nullOrLastname("jonas").ifPresent(System.out::println);
}
You need to declare the variable first: 您需要先声明变量:
String lastname;
if( (lastname=nullOrLastname("jonas")) != null)
{
System.out.println(lastname);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.