Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
Idiomatic way of converting from Long object to long primitive safely in java

I was trying to pass a Long object value to a method that expects long primitive, passing directly works except for the case when 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 calling the method, 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 a elegant/better way to do this? I have to repeat this multiple times in the codebase and doing it like this seems to add a lot of conditionals.

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

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

There's nothing built into Long (e.g., some static method) to do it.

Assuming you have multiple methods accepting long you need to use this with, you'll probably want your own method, something along the lines of

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

Then

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

Of course, that's not a lot shorter than

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

If it's just methodExpects_long_primitive, I'd probably modify it to accept a Long instead, and handle the null within it.

over 4 years ago · Santiago Trujillo Denunciar

0

As of Java 8, one option is to wrap your Long in an java.util.Optional. Wherever possible, pass this around instead of the Long. When you must get a long value, you can provide a default with Optional.orElse():

Long foo = null;

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

System.out.println( longFoo );

Or you can test whether the Optional holds a value with Optional.empty():

    Long foo = null;

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

        System.out.println( longFoo );
    }

One nice side effect of this approach is that it is clear that the value might be null, no matter where you pass the Optional. Another is that an attempt to call get() when the value is null will throw an exception immediately.

Before Java 8, you could use Google's guava library, which provides a very similar class com.google.common.base.Optional.

over 4 years ago · Santiago Trujillo Denunciar

0

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

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

If you do not owe the method you need to handle null out of the method as you wrote

bar.methodExpects_long_primitive(foo==null?defaultValue:foo);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda