How to discard static common functions in java that don't accept parameters?

In a project that I worked on in my 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 the compiler gives me an error:

Cannot drop from Optional <Object> to Optional <User>

More work here that works:

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

How can I avoid creating an empty variable?

+3
source share
2 answers

This is a known bug with type inferencing in the case of a conditional statement. Java generics does not derive types from the return type somehow. The workaround is to give an explicit type argument:

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

Oh and please get rid of == true. It is simply not required. In addition, another conditional statement:

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

:

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

, , , ;-) , :

Optional.<User>absent()

Btw, , :

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

+6

All Articles