Introduction
The ability to use open type declarations, no matter how seemingly small, is perhaps one of the most unique features that was released with F# 5. Essentially, it allows us to pick and choose types from a module to make them available in our code. Let's jump right in.
A Simple Example
For example, let's say that we want to make the Math
type available in our code but leave the rest of the System
namespace out of our scope. We can accomplish this via the following line.
open type System.Math
Once we have the above line in place, we can access the Math
type's members like so.
Max(123., 321.) // Max is a member of type Math.
// Result: 321.0
However, if we try to access some other type that's inside the System namespace, we will get a compiler error.
let rnd = Random() // Random is a type inside the System namespace that has a default constructor.
// Result: Error FS0039: The value or constructor 'Random' is not defined.
Other Use Cases
You can use open type declarations to open your own types, exactly the same way we used it to open a type inside the .NET Base Class Library above.
Let's say that you have the following module.
module Sales =
type Balance = Overdrawn of decimal | Remaining of decimal
// More types and functions...
If all you want to make available from this module is the type Balance
, you don't have to open the whole module anymore. Instead, you can just do the following.
open type Sales.Balance
let myBalance = Remaining of 500. // myBalance is of type Balance.
Closing Thoughts
Thank you for exploring this small yet wonderfully unique new F# feature with me. I hope it will be of use to you in the future!