4 ms·
> Whereas in F# you'll run into this using references It depends :) F#-defined reference types cannot be assigned a null value by default. If your reference i
by phillipcarter 6y ago
> Whereas in F# you'll run into this using references
It depends :)
F#-defined reference types cannot be assigned a null value by default. If your reference is an F# library (or one with F# bindings, of which there are several) then this isn't something you run into. Technically this can be bypassed by giving the type an attribute called AllowNullLiteral, but it is extremely rare to see that in practice because it's so unsatisfactory to use null from a cultural perspective in F#. Once a C# programmer uses F#, something switches on in their brain and they tend to eliminate all possible ways null can creep in as thoroughly as possible. It's neat.
Another aspect where you don't see null is in initialization soundness. In F#, all values must be initialized before use. This is in sharp contrast to C# or Java where you can accidentally access something that hasn't been initialized before. While you can also technically bypass this to inject a null somewhere, it is also exceedingly rare because it's not a default behavior.
F# data types also cannot be assigned a null value, so that's also a place where null doesn't come in.
So it really leaves interop with .NET assemblies, some serialization scenarios, and .NET reflection. The first is really the only time people can still get "surprised" by a _null_ value. The rest are all technically possible, but just tend not to come up.
The reason why this all matters is it's not a binary thing about having null/non-null. Just like it's not a binary thing about having exceptions/vs. not. It's about how frequently they can come about in normal programming scenarios. I can write a simple Haskell program that throws an exception at runtime, does that mean that Haskell is not safe? Of course not, because it's not usually what normal Haskell code does. The same thinking applies here. The ways that null can creep into an F# program are simply smaller than C# or Java and do create this mindset that nullis something that F# programmers tend not to think about that much.