Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f# private class inside public one

Tags:

java

oop

class

f#

I have a Java class and I need to write a similar one in F#. How can I define a private class inside public in f#?

public class KnownRuleGoals {
    void record() {
      knownParsingSet.add(new KnownParsing());
    }

    private class KnownParsing {
        Rule [] knownParsing;
        KnownParsing() {
         ...
        }
        void doWork() { ... }
    }
}
like image 915
Алиса Метелева Avatar asked Jan 25 '16 21:01

Алиса Метелева


1 Answers

It is perfectly possible in F#. F# is functional first, not pure functional - and this is one of its major strengths. F# is pragmatic and this construct below lets one achieve exactly the same result, even though the KnownParsing type is not "nested" in Java or C# sense.

type KnownRuleGoals() =
    let knownParsingSet : List<KnownParsing> = List()
    member this.Record() =
      knownParsingSet.Add(new KnownParsing())

and private KnownParsing() =
    let foo = "private fields"
    member this.DoWork() = failwith "TODO implementation"

Object expressions are useful for implementing interfaces or abstract classes, but the "parent" class (the one that creates an object expression) won't be able to access its internals. Or, more correctly, there is no way to create internals other than interface/abstract members in any way other than via ref cells outside the object expression itself. This has performance implications such as GC pressure for ref cells.

See this example in my open-source project about how object expressions and "nested via and" types work interchangeably for IEnumerator implementation. On this line I use private type as in this answer and it works well. In the whole project I use F# in mostly imperative way because this is the only way to get decent performance. And I must say I like F# most often over C# even for imperative code.

like image 192
V.B. Avatar answered Sep 28 '22 03:09

V.B.