Is there an elegant way to initialize and return a value of a field with a value of zero using Optional

I have a piece of code that returns the value of a single field, but also initializes it:

public Observable<Integer> asObservable() {
    if (subject == null) {
        subject = BehaviorSubject.createDefault(0);
    }
    return subject;
}

I am trying to use a class Optionalto avoid the instruction if:

public Observable<Integer> asObservableWithOptional() {
    Optional.ofNullable(subject)
            .executeIfAbsent(() -> BehaviorSubject.createDefault(0));
    return subject;
}

Hovewer I'm still not happy with this code. Is there a way to turn this metos into one with one statement? Something similar to the following will not work, because it was subjectnot initialized during the ofNullablefactory method call :

    return Optional.ofNullable(subject)
            .executeIfAbsent(() -> BehaviorSubject.createDefault(0))
            .get();

Note. I do not use the original Java8 API, but the aNNiMON port of this API is https://github.com/aNNiMON/Lightweight-Stream-API .

+4
2

return subject = Optional.ofNullable(subject).orElseGet(() -> BehaviorSubject.createDefault(0));

, Optional :

return subject != null ? subject : (subject = BehaviorSubject.createDefault(0));
+7

- :

return (subject == null ? (subject = BehaviorSubject.createDefault(0)) : subject);
+2

Source: https://habr.com/ru/post/1682667/


All Articles