在Java中使用”guard/if let” – 如果可以解包,声明一个属性或对象。

huangapple go评论61阅读模式
英文:

guard/if let in Java - declare a property or an object if it can be unwrapped

问题

在Swift中,有guard let / if let模式,允许我们仅在可以解包时声明对象或属性。

它的工作方式如下:

func getMeaningOfLife() -> Int? {
    42
}

func printMeaningOfLife() {
    if let name = getMeaningOfLife() {
        print(name)
    }
}

func printMeaningOfLife() {
    guard let name = getMeaningOfLife() else {
        return
    }

    print(name)
}

我的问题是:是否有Java版本的类似功能?

英文:

In swift there is the guard let / if let pattern allowing us to declare an object or a property only if it can be unwrapped.

it works a follow:

func getMeaningOfLife() -> Int? {
    42
}

func printMeaningOfLife() {
    if let name = getMeaningOfLife() {
        print(name)
    }
}

func printMeaningOfLife() {
    guard let name = getMeaningOfLife() else {
        return
    }

    print(name)
}

My question here is: Is there a Java version of it ?

答案1

得分: 2

Java没有像这样的guard/let子句。您示例的最接近等价物是使用OptionalInt(或对象的Optional)及其ifPresent方法:

OptionalInt getMeaningOfLife() {
    return OptionalInt.of(42);
}

void printMeaningOfLife() {
    getMeaningOfLife().ifPresent(name ->
            System.out.println(name));
}

请注意,Java确实有一种“较小”的形式的这些类型的子句,以instanceof <typeName> <variableName>的形式进行流类型化,这是通过JEP 394: instanceof的模式匹配引入的。

英文:

Java doesn't have guard/let clauses like this. The closest equivalent of your example is using OptionalInt (or Optional for objects) and its ifPresent method:

OptionalInt getMeaningOfLife() {
    return OptionalInt.of(42);
}

void printMeaningOfLife() {
    getMeaningOfLife().ifPresent(name -&gt; 
            System.out.println(name));
}

Note that Java does have a "lesser" form of these types of clauses in the form of flow-typing using instanceof &lt;typeName&gt; &lt;variableName&gt; introduced with JEP 394: Pattern Matching for instanceof.

答案2

得分: 1

答案是不。

显然,这种语法在Clojure中也存在,根据这个Stack Overflow回答,如果可以在Java中取消包装,就没有办法声明一个属性。

英文:

The answer is No.

Apparently this syntax also exists in Clojure and according to this Stack Overflow answer there is no way to declare a property if it can be unwrapped in Java.

答案3

得分: 0

这个技巧就是,没有所谓的条件声明。实际上发生的是,条件引入了一个新的作用域,在这个作用域中变量总是被声明,或者引入了一个防卫条件以进行短路操作。

Java 也可以做到类似的事情,尽管从词法上来看可能没有那么漂亮。

Integer getMeaningOfLife() {
    return 42;
}

void printMeaningOfLife() {
    { //这个大括号引入了一个新的作用域
        Integer name = getMeaningOfLife();
        if (name != null) {
            print(name);
        }
    } //关闭作用域
    //name 现在超出了作用域,无法使用
}

void printMeaningOfLife() {
    Integer name = getMeaningOfLife();
    if (name == null) {
        return;
    }
    print(name);
}

这基本上就是你已经自己想明白的,除了第一个 printMeaningOfLife() 中引入作用域的大括号可能除外。

英文:

The trick is that there is no such thing as a conditional declaration. What's really happening is that the conditional is introducing a new scope in which the variable is always declared, or a guard condition which short-circuits.

Java can do the same, though lexically it is not as pretty.

Integer getMeaningOfLife() {
    return 42;
}

void printMeaningOfLife() {
    { //this brace bracket introduces a new scope
        Integer name = getMeaningOfLife();
        if (name != null) {
            print(name);
        }
    } //closes scope
    //name is now out of scope and cannot be used
}

void printMeaningOfLife() {
    Integer name = getMeaningOfLife();
    if (name == null) {
        return;
    }
    print(name)
}

This is basically what you have already figured out for yourself, except maybe for the brace brackets which introduce scope in the first printMeaningOfLife().

huangapple
  • 本文由 发表于 2023年6月2日 12:32:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定