简体   繁体   中英

Null Vs Option in F#

I have a problem understanding co-existence of "null" and Option in F#. In a book I have read that null value is not a proper value in F# because this way F# eliminates the excessive null checking. But it still allows null-initialized references in F#. In other words, you can have null values but you don't have the weapons to defend yourself with. Why not completely replace nulls with Options. Is it because of compatibility issues with .NET libraries or languages that it's still there? If yes can you give an example that shows why it can't be replaced by Option?

F# avoids the use of null when possible, but it lives in the .NET eco-system, so it cannot avoid it completely. In a perfect world, there would be no null values, but you just sometimes need them.

For example, you may need to call .NET method with null as an argument and you may need to check whether a result of .NET method call was null .

The way F# deals with this is:

  • Null is used when working with types that come from .NET (When you have a value or argument of type declared in .NET, you can use null as a value of that type; you can test if it equals null )

  • Option is needed when working with F# types, because values of types declared in F# cannot be null (And compiler prohibits using null as a value of these types).

    In F# programming, you'll probably use option when working with .NET types as well (if you have control over how their values are created). You'll just never create null value and then use option to have a guarantee that you'll always handle missing values correctly.

This is really the only option. If you wanted to view all types as options implicitly when accessing .NET API, pretty much every method would look like:

option<Control> GetNextChild(option<Form> form, option<Control> current);

...programming with API like this would be quite painful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM