An idiomatic way to transition from a long object to a long primitive is safe in java

I tried to pass the Long value of an object to a method that expects a long primitive, the transfer works directly, unless the Long object is null. In this case, I get a Null Pointer exception.

Long foo=null;
bar.methodExpects_long_primitive(foo);

I can create a check if foo is null and skip the method call like

Long foo=null;
if(foo!=null){
bar.methodExpects_long_primitive(foo);
}

or if I want to provide a default value

Long foo=null;
bar.methodExpects_long_primitive(foo==null?defaultValue:foo);

Is there an elegant / best way to do this? I have to repeat this several times in the codebase and do it, it seems, adds a lot of conventions.

I could create my own method for this, but I would like to know if there is any such library method.

+4
source share
3

Java 8, , Long java.util.Optional. , , "". , Optional.orElse():

Long foo = null;

Optional<Long> optFoo = Optional.ofNullable( foo );
long longFoo = optFoo.orElse( -1L );

System.out.println( longFoo );

, Option Optional.empty():

    Long foo = null;

    Optional<Long> optFoo = Optional.ofNullable( foo );
    if ( ! optFoo.empty() ) {
        long longFoo = optFoo.get();

        System.out.println( longFoo );
    }

, , , , . , get(), null, .

Java 8, Google guava library, com.google.common.base.Optional.

+2

Long (, ).

, , Long, , , , , -

// On some utility class, say LongUtil
public static long val(Long l, long defaultvalue) {
    return l == null ? defaultValue : l.longValue();
}

bar.methodExpects_long_primitive(LongUtil.val(foo, defaultValue));

,

bar.methodExpects_long_primitive(foo == null ? defaultValue : (long)foo);

methodExpects_long_primitive, , , , Long null .

+1

just change your method to get a Long object and then check for null

T methodExpects_long_primitive(Long l) {
    long foo = (l != null) ? l : 0L;

If you should not use a method that should handle null from a method, as you wrote

bar.methodExpects_long_primitive(foo==null?defaultValue:foo);
+1
source

Source: https://habr.com/ru/post/1673038/


All Articles