How to cast from static generic functions in java that don't take parameters?

generics, guava, java

Solution

This is a known bug with type inferencing in case of conditional operator. Java generics doesn't infer the types from the return type some how. The workaround is to give explicit type argument:

return success == true ? Optional.of( user ) :Optional.<User>absent ( );

Oh, and please get rid of `== true`. That is simply not required. Also, the other conditional operator:

 boolean success = ( user == null ) ? false 
                                    : user.password.equals( request.password );

can be replaced with:

boolean success = (user != null) && user.password.equals( request.password )

Problem

In the project that i've been working on i user guava library. I have something like this: ``` Optional< User > loginUser( ) { User user = storage.get( request.id ); boolean success = ( user == null ) ? false : user.password.equals( request.password ); return success == true ? Optional.of( user ) :Optional.absent ( ); } ``` and compiler gives me the error: Cannot cast from Optional< Object > to Optional< User > More over here is work around that works: ``` Optional< User > empty = Optional.absent ( ); return success == true ? Optional.of( user ) : empty; ``` How can I escape from creating empty variable ?

Original source