0

I am quite new to the concept of Optional. In the code posted below, i am checking the following:

if (operation_1) {

    if (operation_2) {

        if (operation_3) {

        } else {
            throw_3
        }
    } else {
        throw_2
    }
} else {
    throw_1
}

but for this code, android studio, generates an error for the second orElseThrow() operation "marked below". please let me why I receive this error?how to fix it? whether or not the code i wrote below satisfies the conditions shown above.

code:

OptionalsUtils.toOptional(Room.databaseBuilder(getApplicationContext(), MovieDatabase.class, ActMain.DATA_BASE_NAME))//operation_1
            .map(x->{
                MovieDatabase movieRoomDb = x.fallbackToDestructiveMigration().build();
                this.setInitializedBuiltMovieRoomDatabase(movieRoomDb);
                return movieRoomDb;
            })//operation_2
            .map(y->{
                SupportSQLiteOpenHelper openHelperInstance = y.getOpenHelper();
                this.setSQLOpenHelperInstance(openHelperInstance);
                return openHelperInstance;
            })//operation_3
            .orElseThrow(()-> new NullPointerException(THROW_SQL_OPEN_HELPER_NULL))//throw_3
            .orElseThrow(()-> new NullPointerException(THROW_ROOM_DATABASE_PERSISTENT_BUILD_NULL))//throw_2<-cases error
            .orElseThrow(()-> new NullPointerException(THROW_ROOM_DATABASE_PERSISTENT_BUILDER_NULL));//throw_1
Eran
  • 387,369
  • 54
  • 702
  • 768
user10776303
  • 241
  • 6
  • 16

1 Answers1

1

I wouldn't recommend using an Optional here as it's not meant to replace simple "if" cases.

instead, invert the if conditions to remove the nesting:

if (!operation_1) 
   throw_1;
if(!operation_2)
   throw_2;
if(! operation_3)
   trow_3;

...  
...

As for your code, you cannot just chain orElseThrow methods as shown because the first call to orElseThrow will return the value encapsulated within the Optional if present otherwise throws the supplied exception thus the result of this method call is no longer an Optional.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • thanks, but would you please tell me why optional in this case should not replace if-statements? – user10776303 Dec 14 '18 at 13:15
  • @user10776303 see the accepted [answer here](https://stackoverflow.com/questions/53504573/is-using-optional-ofnullable-as-a-replacement-for-the-ternary-operator-a-good-pr) – Ousmane D. Dec 14 '18 at 13:17