Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't F# support nested classes?

Tags:

f#

Is the reason F# doesn't support nested classes technical, stylistic, arbitrary?

Glancing over the BCL in Reflector, nested classes are used for enumerators, DynamicMetaObjects, and probably a few other things.

That piqued my curiosity about F# not having this feature. I'm aware that there are other ways to do the same thing. I'm mostly curious.

like image 860
Daniel Avatar asked Jan 20 '12 21:01

Daniel


2 Answers

I suppose nested classes were not a core feature of the .NET object model and it was simply dropped to save the resources. There may be some technical difficulties (i.e. with visibility or with recursive type definitions), but I don't think that would be a major problem.

For many cases where one would use nested classes in C#, such as iterators, you can nicely use object expressions, so I guess they are in some ways replacement for nested classes:

type Collection() =
  member x.GetEnumerator() = 
    let n = ref 0
    { new IEnumerator with
        member x.Current = box n.Value
        member x.MoveNext() = incr n; true
        member x.Reset() = n := 0 }

Although this is quite similar to nested classes, it isn't compiled as nested class and the body of an object expression cannot access private members of Collection. I guess supporting this would complicate compilation of expressions a bit, because object expressions can appear outside of a class context...

Actually, it is possible to access private members from object expression, although the code still isn't compiled as a nested class. See comments for details.

like image 69
Tomas Petricek Avatar answered Nov 08 '22 08:11

Tomas Petricek


F# is largely based on Caml, which does not have nested classes.

It probably wasn't added simply because it's not very high-priority. Since you can declare data types that are not visible outside of a module, allowing inner classes would not make all that much of a difference in how well-encapsulated your code can be.

like image 34
Sean U Avatar answered Nov 08 '22 09:11

Sean U