Correct way to check Scala NULL in Java

2

First, I want to say that I am totally lay in Scala. I know almost nothing beyond the basics of language. Knowing this, let us doubt it.

I'm in a project where there are libraries developed in Scala. These libraries were packaged in JAR's and I import the Java project. So far so good. I do not have access to the fonts of these libraries in Scala.

What happens is that sometimes I need to compare null . In Java this is one way and by the way Scala seems to be otherwise.

Let's take a practical example to illustrate my problem. Let's suppose that my scaled lib returns an object Usuario :

Usuario user = usuarioService.getUsuario(usuarioID);
System.out.println(usuario.nome().get());
System.out.println(usuario.email().get());

In the example above I'm using the lib made in Scala and searching for information from a User. Everything is Scala object, from the lib in Scala.

Now, I want to check whether the nome attribute, for example, is nulo or not. I saw two forms. One that I believe to be Java Way and another Scala Way .

Java Way

final scala.Option<String> None = scala.Option.apply(null);
Usuario user = usuarioService.getUsuario(usuarioID);
if (!user.nome().equals(None)) {
    System.out.println(usuario.nome().get());
}

Scala Way

Usuario user = usuarioService.getUsuario(usuarioID);
if (user.nome().nonEmpty()) {
    System.out.println(usuario.nome().get());
}

Now the question, what is the best way to do this when developing in Java and using libs made in Scala?

    
asked by anonymous 15.07.2015 / 16:01

1 answer

3

Java 8 brings a new API to avoid verbosity and excessive "checks" to null and consequently unwanted NPE by methods that indicate the lack of a possible return value.

This is the same purpose of Scala.option .

In Java 8 the API name is Optional . Home Applying to your code we would have:

First we change the return of < usuarioService.getUsuario.getUsuario by adding Optional .

public Optional<Usuario> getUsuario(String usuarioID) {

Now you just have to use the API to check for a return :

Optional <Usuario> user = usuarioService.getUsuario(usuarioID);
if (user.isPresent()) {
    System.out.println(user.get().nome().get());
}

Take a deeper look at the Oracle document:
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!

    
20.07.2015 / 01:01