Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In F#. Is it possible to overload constructor of an abstract type?

If yes could you give an example of a type with parameterless and "parameterfull" constructor.

Is that something you would recommend using or does F# provide some alternative more functional way. If yes could you please give an example of it?

like image 706
Enes Avatar asked Nov 06 '22 18:11

Enes


1 Answers

Like this?

type MyType(x:int, s:string) =
    public new() = MyType(42,"forty-two")
    member this.X = x
    member this.S = s

let foo = new MyType(1,"one")
let bar = new MyType()
printfn "%d %s" foo.X foo.S    
printfn "%d %s" bar.X bar.S    

This is the typical way to do it. Have the 'most parameterful' constructor be the implicit constructor, and have the rest be 'new' overloads defined as members in the class that call into the implicit constructor.

EDIT

There is a bug in Beta2 regarding abstract classes. In some circumstances you can work around it using default arguments on the implicit constructor, a la

[<AbstractClass>]
type MyType(?cx:int, ?cs:string) =
    let x = defaultArg cx 42
    let s = defaultArg cs "forty-two"
    member this.X = x
    member this.S = s
    abstract member Foo : int -> int

type YourType(x,s) =
    inherit MyType(x,s)    
    override this.Foo z = z + 1

type TheirType() =
    inherit MyType()    
    override this.Foo z = z + 1

let foo = new YourType(1,"one")
let bar = new TheirType()
printfn "%d %s" foo.X foo.S    
printfn "%d %s" bar.X bar.S    
like image 180
Brian Avatar answered Nov 14 '22 22:11

Brian