1 people like it.

Multi construct for class in F#

When we defined an F# class in explicit way, it's easy for new F# programmers to make this kind of mistakes when they define mult constructors: people will forget to initliza the class first before use it.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
type myCls() = 
    //This this a new feature in VS2012,define a property is much easier than before.
    member val Value = 0 with get,set

    member this.Print() =
        printfn "%d" this.Value

    //Must initilaize the second construct by the default one before set the property Value
    new(value : int) as this = 
        new myCls()
        then
            this.Value <- value
Multiple items
type myCls =
  new : unit -> myCls
  new : value:int -> myCls
  member Print : unit -> unit
  member Value : int
  member Value : int with set

Full name: Script.myCls

--------------------
new : unit -> myCls
new : value:int -> myCls
val set : elements:seq<'T> -> Set<'T> (requires comparison)

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.set
val this : myCls
member myCls.Print : unit -> unit

Full name: Script.myCls.Print
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
property myCls.Value: int
val value : int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
Raw view Test code New version

More information

Link:http://fssnip.net/el
Posted:12 years ago
Author:ZackZhou
Tags: constructor;f#