Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird accessibility scopes when F# record's fields are declared private

Tags:

f#

I just noticed a rather counter intuitive behaviour when the field part of an F# record is declared private. (This is related to Is it possible to make a field of a record private? or to make a member of record private?)

In this example...

type MyRec = 
    private  // Fields declared private, or at least I thought so.
        { a : int
          b : int }
    member x.A = x.a
    member private x.Both = x.a + x.b
    static member CreateMyRec(a, b) = { a = a; b = b }

let foo = MyRec.CreateMyRec(1,2)
let bar = foo.a     // No error. Huh?
let baz = foo.Both  // Error: not accessible.

...the private member Both is inaccessible outside the type declaration scope, as is expected. However, the field a is accessible.

If you put MyRec in a module, the fields become private to that module. That's how you'd expect a top level declaration in the module to behave, but I expected that anything declared private within a type, would be private to that type, not to its enclosing module.

Is this behaviour actually weird, or am I missing something in my reasoning here?

like image 227
John Reynolds Avatar asked Jan 22 '13 15:01

John Reynolds


1 Answers

As far as I can tell, this is an under-documented feature. But, section 10.5 of the spec, Accessibility Annotations, states:

private on a type, module, or type representation in a module means “private to the module.”

"type representation" being the part relevant to record fields.

like image 100
Daniel Avatar answered Nov 19 '22 02:11

Daniel