Is there an elegant way to initialize and return value of nullable field using Optional

Viewed 903

I have a piece of code which returns value of one field, but also initializes it:

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

I'm trying to use Optional class to avoid if statement:

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 methos into one with one statement only? Something similar to following won't work because subject have not been initialized during call to ofNullable factory method:

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

Note: I'm not using original Java8 API, but aNNiMON port of this API https://github.com/aNNiMON/Lightweight-Stream-API.

2 Answers
Related