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
Reblogged this on himanshu2014.
Reblogged this on Play!ng with Scala and commented:
Java null in Scala