Correct form of Scala NULL checking in Java

Asked

Viewed 122 times

2

First of all, I want to say that I’m a total layman in Scala. I know almost nothing but the basics of language. Knowing this, let’s go to my question.

I am in a project where there are libraries developed in Scala. These libraries have been packaged in JAR’s and I import in the Java project. So far so good. I don’t have access to the sources 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 another way.

Let’s take a practical example to illustrate my problem. Let’s assume 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 above example I am using the lib made in Scala and seeking information from a User. Everything is Scala object, from lib in Scala.

Now, I want to check if the attribute nome, for example is nulo or not. I saw two ways. 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, how best to do this when developing in Java and using libs made in Scala?

1 answer

3


Java 8 brings a new API to avoid verbosity and excessive "checks" to null and therefore unwanted NPE through methods indicating the lack of a possible return value.

That’s the same purpose of Scala.option option.

In java 8 the name of the API is Optional.

Applying to your code we would have :

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

public Optional<Usuario> getUsuario(String usuarioID) {

Now just use the API to check the existence of a return:

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

Follow a more in-depth view in the Oracle document:
Tired of Null Pointer Exceptions? Consider Using Java SE 8’s Optional!

  • 1

    I found Optional very interesting! I did some experiments here and it’s really cool. Thanks for the tip.

  • Exactly Reginaldo, this way is very interesting and brings a functional Smell to the language. Interestingly, Optional in Java tb is a Monad. http://learnyouahaskell.com/a-fistful-of-monads#Monad-Laws

Browser other questions tagged

You are not signed in. Login or sign up in order to post.