Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a field of a record private? or to make a member of record private?

Tags:

f#

I want to stick with record, and don't want to go back to object. So I am wondering if it is possible to make a field of a record private? or to make a private member of record. what about other concrete types such as discriminated union?

Or, does this requirement violate the language spec?

like image 704
colinfang Avatar asked Sep 12 '12 13:09

colinfang


1 Answers

Nope, it's not possible for single fields to be private: http://msdn.microsoft.com/en-us/library/dd233184

However, you can make all fields private and expose selected fields through properties. Note that you will need a Create-function in order to create an instance of the records, since its' fields are private:

type MyRec = 
    private
        { a : int
          b : int }
    member x.A = x.a
    member private x.Both = x.a + x.b  // Members can be private
    static member CreateMyRec(a, b) = { a = a; b = b }

Members can be private though, as in the case of the MyRec.Both property above.

Edit: The above makes the fields private to the module that MyRec is defined in, not private to MyRec. See Daniel's answer to Weird accessibility scopes when F# record's fields are declared private.

like image 143
John Reynolds Avatar answered Oct 18 '22 00:10

John Reynolds