How to instantiate a class and populate properties in F #?

In C #, I can:

var n = new Person()
{
     FirstName = "John",
     LastName = "Smith"
};

Can I do the same in F #? I mean, to create a class and specify some properties.

+3
source share
3 answers

Yes:

let n = Person(FirstName = "John", LastName = "Smith")

Note that the F # approach is actually much more flexible than the C # approach, since you can use the post hoc property assignments by any method call (and not just the constructors). For example, if the type Personhas a static method called CreatePerson : string -> Personthat creates a new person and assigns the first name, you can also use it as:

let n = Person.CreatePerson("John", LastName = "Smith")
+12
source

F # , , , .

type Person = {
    FirstName : string;
    LastName : string;
}

let p = {FirstName = "John"; LastName = "Smith"}
+3
type Person() =

    [<DefaultValue>]
    val mutable firstName : string

    [<DefaultValue>]
    val mutable lastName : string

    member x.FirstName 
        with get() = x.firstName 
        and set(v) = x.firstName <- v

    member x.LastName 
        with get() = x.lastName 
        and set(v) = x.lastName <- v

let p = new Person(FirstName = "Nyi", LastName = "Than")
+2
source

Source: https://habr.com/ru/post/1790492/


All Articles