5
votes

In F#, if you are interoperating with another .NET language, or if you using the AllowNullLiteral attribute, a reference type can be null. The example that comes to mind right away are strings:

let str: string = null

But with C# 8 and dotnet core 3, we can opt in to Nullable Reference Types. I would have to write the above code in C# like:

string? str = null;

Is there a way to also opt in to Nullable Reference Types in F# so that types defined in other languages cannot be null, and if they could be, write them as a Nullable Reference like:

let str: string = null // error cannot do this
let str: string? = null

I'm aware that we can convert types that might be expected to be null by using Options:

let str : string = null
let strOpt = Option.ofObj str

My question is: Is there away that makes it impossible to make a reference type null, like string, without explicitly declaring it to be nullable in F#?

1
You actually don't need .NET Core just C# 8Aluan Haddad

1 Answers

4
votes

From https://www.infoq.com/news/2019/04/FSharp-Nulls/,

"F# currently supports several versions of nullability. First there are normal .NET reference types. Today there is no way to unequivocally inform the compiler if a specific reference type variable is nullable or not, so their use in F# is discouraged."

"The preferred alternative is Option. Also known as a “maybe” type, this is a type- safe way to express the concept of nullability. When used with idiomatic F# code, you can only read the value after checking to see if it is non-null (not “none” in F# parlance). This is usually done via pattern matching."

However, the desire that there would be a clean way to interop with these ? annotations is recognized by the F# team, and a proposal for nullable reference types can be found here. As of today, the proposal is "Approved in principle" but no prototype implementation yet exists.