Working Effortlessly with Java null in Scala

Table of contents
Reading Time: 2 minutes

We would not repeat why null is a billion dollar mistake of Java. In our earlier post, we have already discussed how to handle nulls of Java. In this post we would take it a step further, but first a bit of recap.

Say that you have a function in Java which can potentially throw a null.

Now, the way we have been handling this in Scala has been with fold. So what we would do is

Hence, if the Option(getUser) results in None then we give the default value which is “Sky” else if it is Some then we pass it to a method called processUser which brings us back the name. Hence it is of the type User=>String

Now what is the problem with this approach, actually none but it just leads to quite some boilerplating if we are working with quite a few Java methods which can return null because everytime we would be writing statements like

Option(getUser).fold(“Sky”)(u=>processUser(u))

Let us get it into a common object.

and now how we would use it for the above scenario

No folds, no options and just SValue (Scala Value). You can pass the defautValue explicitly or you can let it be picked up from the implicit scope. The gist for the code is present here.

Ok, so far so good. But what if we would like to defer the function for later. We want to do currying it. How do we do that

Now, how do we call it this time. We know that if the value is null what would be the default vlaue but if the value is not null then we would like to apply a function to process later.

This gives us f which is a partially applied function. Now how do we apply it later

If you notice, the beauty of the above code is now that Scala is Type inferring our datatype and hence we are just able to call _.name on it. Enjoy, the gist is here

Written by 

Rachel Jones is a Solutions Lead at Knoldus Inc. having more than 22 years of experience. Rachel likes to delve deeper into the field of AI(Artificial Intelligence) and deep learning. She loves challenges and motivating people, also loves to read novels by Dan Brown. Rachel has problem solving, management and leadership skills moreover, she is familiar with programming languages such as Java, Scala, C++ & Html.

2 thoughts on “Working Effortlessly with Java null in Scala2 min read

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading