Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda