F # Constructor Syntax - Override and Add New

I have a non-disposable class with Open / Close syntax that I would like to be able to use , so I'm trying to inherit from it, and work Open in new and Close in Dispose.

The second part is fine, but I cannot decide how to make Open:

 type DisposableOpenCloseClass(openargs) = inherit OpenCloseClass() //do this.Open(openargs) <-- compiler no like interface IDisposable with member this.Dispose() = this.Close() 

(see this question that I asked a long time ago, but I can’t connect the dots to this)

+7
syntax constructor f #
source share
2 answers

Key as this :

 type OpenCloseClass() = member this.Open(x) = printfn "opened %d" x member this.Close() = printfn "closed" open System type DisposableOpenCloseClass(openargs) as this = inherit OpenCloseClass() do this.Open(openargs) interface IDisposable with member this.Dispose() = this.Close() let f() = use docc = new DisposableOpenCloseClass(42) printfn "inside" f() 
+10
source share

As Brian suggests, you can use the as this clause. However, in F # it is usually recommended to use a subclass (inheritance) only when there is a really good reason for this (for example, you need to implement some kind of virtual class and pass it to the .NET library).

If I implemented your example, I would prefer the return IDisposable function with a simple object expression:

 let disposableOpenClose(openargs) = let oc = new OpenCloseClass() oc.Open(openargs) { new IDisposable with member this.Dispose() = oc.Close() } let f() = use docc = disposableOpenClose(42) printfn "inside" 

At some point, this is just a personal preference, but I think this is the preferred option because it is simpler than using inheritance (although I don't have any document for reference here :-)). Also, compiled code might be a little simpler, as some execution checks may be required to process as this .

+4
source share

All Articles