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?
I found Optional very interesting! I did some experiments here and it’s really cool. Thanks for the tip.
– humungs
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
– Filipe Miranda