Inheritance Type in F #

I cannot find the correct syntax for type D encoding that inherits the base class B (written in C #) and its constructors other than the implicit constructor of the base class:

C # code:

public class B { private int _i; private float _f; public B() { _i = 0; _f = 0.0f; } public B(int i) { _i = 0; _f = 0.0f; } public B(int i, float f) { _i = i; _f = f; } } 

Code F #:

 type D() = inherit B() //how to inherit from other constructors ? 

thanks

+4
source share
2 answers

I found a way to do this thanks to this blog !

 type D = class inherit B new () = { inherit B() } new (i : int) = { inherit B(i) } new ((i,f) : int*single) = { inherit B(i, f) } end 

Yes, it's a little cumbersome, but, as Brian said, this is not the majority of cases.

EDIT: Actually class / end keywords are not required for this (so I am returning what I said about cumbersomeness). As Brian said in his blog here , F # usually defines a type of a specific type, making these tokens unnecessary / redundant.

 type D = inherit B new () = { inherit B() } new (i : int) = { inherit B(i) } new ((i,f) : int*single) = { inherit B(i, f) } 
+6
source

In the docs: "Arguments for the base class constructor appear in the argument list in the inherit clause." For instance:

 type D(i: int) = inherit B(i) 

I'm not sure if different constructors of the base class can be called from different F # constructors, because F # requires that all constructors go through the "primary" constructor (since the arguments of the primary constructor are available for the whole class, so they have to be initialized). In your case, you can avoid this because your base class has a max constructor:

 type D(i : int, f : float) = inherit B(i, f) new(i : int) = D(i, 0.0) new() = D(0, 0.0) 

But for a base class without a maximum constructor, I'm not sure if this is possible.

+5
source

All Articles