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

If so, you can give an example of a type without parameters and the constructor "parameterfull".

This is something you would recommend using or F # provides an alternative, more functional way. If so, can you give an example?

+5
source share
1 answer

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 a typical way to do this. Create the "most parameterful" constructor as the implicit constructor, and the rest - the "new" overloads, defined as members of the class that invoke the implicit constructor.

EDIT

Beta2 . , , 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    
+2

All Articles