Search code examples
javaswiftoption-type

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


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 ?


Solution

  • 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.