I’m curious if there are things in the standard class library that you find useful but not widely used.

  • JackbyDevOPM
    link
    fedilink
    English
    arrow-up
    2
    ·
    2 years ago

    I’ve waffled on it. Currently my opinion is to use whatever nullable annotation the project uses (if any, otherwise JetBrains’s). Essentially, I’m not sure if the official recommendation to avoid Optional for uses other than return types has reasoning I’m missing.

    I do use it like this though and lament that we don’t have an Elvis operator (?:)

    Optional.ofNullable(thingThatMightBeNull).map(e -> e.someMethod()).orElse(null);
    
      • austin
        link
        fedilink
        English
        arrow-up
        1
        ·
        edit-2
        1 year ago

        Optional has more syntactic sugar for more complex scenarios / functional call chaining that prevents repetitive if checks

        Optional.ofNullable(myObj)
          .map(MyClass::getProperty)
          .map(MyOtherClass::getAnotherProperty)
          .filter(obj -> somePredicate(obj))
          .orElse(null)
        

        This is completely null safe, the function calls are only made if the object is not null