views:

185

answers:

1

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?

+2  A: 

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
Brian
yes but it has to be an abstract type
Wow, you're right, make it an abstract class and it doesn't work. That's a bug; I've filed it. Thanks for asking the question!
Brian
great .... well not really but thanks for the answer anyway. In the meantime is there a workaround to accomplish this? I mean other than making the class non abstract.
No workaround that I am aware of. Of course you can just have the one constructor and then "replicate the defaults" in every derived class.
Brian
Oh, if the other constructors merely do 'default values', you can use the workaround I posted in the edit of my main answer above.
Brian