Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 216
Piotr Aleksander Chmielowski Avatar asked Jan 03 '23 16:01

Piotr Aleksander Chmielowski


1 Answers

How about

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

of course, you can use a ternary conditional operator instead of creating an Optional just to discard it immediately:

return subject != null ? subject : (subject = BehaviorSubject.createDefault(0));
like image 168
Eran Avatar answered Jan 13 '23 16:01

Eran