Access modifiers in F#
April 16, 2017 Leave a comment
F# has the public, private and internal keywords to indicate the access level of a member. If the access level is not specified then it is public by default like here:
namespace com.mycompany.domains.address type Address = { street: string; city: string; number: int; } namespace com.mycompany.domains.order open com.mycompany.domains.address type Order (product:string, value: int, address:Address) = member this.Product = product member this.Value = value member this.Address = address
The Address record, the Order object and its members are all public i.e. they can be accessed from anywhere in the solution. We can restrict the access to private using the “private” keyword which makes the member accessible only from within the containing module:
module AddressModule = type Address = { street: string; city: string; number: int; } with member this.evenNumber = this.number % 2 = 0 let private sumFunction x y = x + y module OrderModule = type Order (product:string, value: int, address:Address) = member this.Product = product member this.Value = value member private this.Address = address
The Address record is public but the “sumFunction” function is not visible outside the module. Also, Order has a private getter/setter on its Address field.
Records cannot have private fields. The following declaration is invalid:
type Address = { street: string; city: string; private number: int; }
This gives the following compiler error:
Accessibility modifiers are not permitted on record fields. Use ‘type R = internal …’ or ‘type R = private …’ to give an accessibility to the whole representation.
The record itself can be private:
type Address = private { street: string; city: string; number: int; }
…or…:
type private Address = { street: string; city: string; number: int; }
If we try to construct an Address record from outside the enclosing module then we’ll get a different compiler error:
The union cases or fields of the type ‘Address’ are not accessible from this code location
The “internal” keyword lies between public and private. Internal members can only be accessed from within the same assembly.
View all F# related articles here.