F# Object and Classes Constructor
In F#, objects and classes are created using the type
keyword. A constructor is a special method that is used to create and initialize objects of a class.
Syntax
Here is the syntax for creating a class constructor in F#:
type ClassName(param1: Type, param2: Type, ...) =
let mutable var1 = initial_value
let mutable var2 = initial_value
new (param1: Type, param2: Type, ...) =
let obj = new ClassName()
obj.var1 <- param1
obj.var2 <- param2
obj
In this example, we define a class with two mutable variables var1
and var2
. A constructor is defined with the new
keyword that takes the same parameters as defined in the type
declaration. The constructor method initializes the variables with the passed parameters and returns the object instance.
Example
Here's an example of a simple F# class with a constructor:
type Person(name: string, age: int) =
let mutable _name = name
let mutable _age = age
member this.Name with get() = _name and set(value) = _name <- value
member this.Age with get() = _age and set(value) = _age <- value
new () = Person("John Doe", 30)
In this example, we define a Person
class with two properties Name
and Age
. We also define a constructor that takes no parameters and initializes the Person
object with default values.
Output
To use the Person
class, we create an instance of the class by using the constructor and passing the required parameters.
let person1 = Person("Bob", 25)
printfn "%s is %d years old" person1.Name person1.Age
let person2 = Person()
printfn "%s is %d years old" person2.Name person2.Age
The output of this code will be:
Bob is 25 years old
John Doe is 30 years old
Explanation
In this example, we create two Person
objects. One is created using the constructor that takes name and age as parameters, and the other is created using the default constructor that has no arguments. We then print the values of the Name
and Age
properties for each object.
The output shows that the first object person1
is initialized with the values "Bob" and 25, while the second object person2
is initialized with default values "John Doe" and 30.
Use
Constructors are useful for initializing object state and setting properties when an object is created. They are also useful for setting default values for object properties.
Important Points
- A constructor is a special method that is used to create and initialize objects of a class.
- In F#, constructors are defined using the
new
keyword. - Constructors can take arguments that are used to initialize the object properties.
- By default, F# creates a default constructor, which initializes the object with default values.
Summary
In this page, we discussed the syntax and example of creating a class constructor in F#. We also discussed the output, explanation, use, and important points of class constructors. Constructors are an important part of building classes in F# as they help to initialize object state and set properties when the object is created.