Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type inheritance in F#

I can't find the proper syntax for coding a type D that inherits a base class B (written in C#) and his constructors other than the base class implicit constructor:

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;
    }
}

F# code:

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

Thanks

like image 432
Stringer Avatar asked Dec 18 '22 05:12

Stringer


1 Answers

I found a way to do it thanks 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 bit cumbersome, but like Brian said it's not the majority of the cases.

EDIT: Actually, class/end keywords are not mandatory for that (so I take back what i said about cumbersomeness). As Brian said on his blog here, F# normally infers the kind of type being defined, 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)
    }
like image 116
Stringer Avatar answered Jan 02 '23 00:01

Stringer