3 ms·
In other languages that use Option types more natively, like Scala, anything that isn't optional is assumed to just not be null: The compiler doesn't guarantee
by hibikir 11y ago
In other languages that use Option types more natively, like Scala, anything that isn't optional is assumed to just not be null: The compiler doesn't guarantee it (it's not as if it can, we are dealing with a JVM here) but it works in practice. I've not seen a NullPointerException in years.
Option has other advantages, like its compositional qualities (thanks to Option being a monad). So imagine the following code
def foo(x:Option[String]) = x.filter(_.length<10).map(_ + "More data")
If the function returns None if it receives either None or a string longer than 10 characters, and if we got Some("short "), foo will return Some("short More data"). The alternatives without an option type, involve at least a couple of branching statements, even if you have a non nullable type, to convert from nullable to not nullable, while Option does it all for us.
- the_af 11y ago> I've not seen a NullPointerException in years [in Scala] This sounds odd. Does your code never interface with Java libraries and frameworks? I envy you! It's all too easy to forget to wrap a suspect value from Java-land with an Option(..). And cumbersome even if you do remember. And then, there's the code written by Scala novices who just love using nulls. Yes, yes, "code reviews", we all know they are always practiced all the time :/
- mark242 11y agoThe Scala landscape is very, very quickly creating their own libraries for similar popular Java libraries/frameworks. It is entirely possible to create an application, web or otherwise, that uses no Java libraries at all (save for the sbt dependency tree). As for "Scala novices who just love using nulls", if you're seeing that, then the coder in question missed day 1 of Scala training, which is always "if you are writing the word null, you are doing something wrong" (right up there with "if you are writing the word var, you are probably doing something wrong").
- the_af 11y agoMaybe, but if true that's still in the future. The OP claimed they hadn't seen a NPE "in years", which simply doesn't match my own experience. As for novices: yes, novices tend to do that. They tend to miss, misremember or fail to put into practice what they should have learned on day 1. I've also seen senior devs who were not exactly newbies (in general) still using nulls because they don't grok Scala; the famous "you can program Fortran in any language". The reality of software development is that you have to deal with all these people.