Monday, March 7, 2011

Studying F# : Constructor

In any other object-oriented languages, "This class has one constructor" means there is only one definition. But, F# is not. F# distinguishes primary constructor from non-primary constructor.

Primary constructor

[<Class>]
type Person(fn, ln, a) =
    member p.FirstName = fn
    member p.LastName = ln
    member p.Age = a

The primary constructor is beside of type definition. Both field definitions for constructor arguments and initialization for fields are defined implicitly by F#.

Non-primary constructor

[<Class>]
type Person =
    val firstName : string
    val lastName : string
    val age : int32
    new(fn, ln, a) = {
        firstName = fn
        lastName = ln
        age = a
    }
    member p.FirstName = p.firstName
    member p.LastName = p.lastName
    member p.Age = p.age

The non-primary constructor exists under the field definitions. beside of type definition. Both field definitions for constructor arguments and initialization for fields are defined explicitly by you.

No comments:

Post a Comment