简体   繁体   中英

F# Object constructor

After recently picking up a bit of C# after a long time of F#, I came to realise that 'object constructors' are a nice way of tricking oneself into believing they are dealing with a functional object.

Consider:

let x = new Something()
x.Key <- 1
x.Value <- 2

This feels very unclean because of the very obvious mutation of values. Especially if we keep our objects write once, it feels very unnecessary In C#, it is possible to initialise the object like this:

var x = new Something() { Key = 1, Value = 2 };

This looks nicer and actually it felt like I was using a record (almost), obviously its just sugar but its nice sugar.

Q. Assuming we have no control over `Something' (pretend its from some C# library), is it possible, in F# to use this shorthand initialisation, if not, why?

Yes, you can do that. It would look something like this:

let x = new Something(Key = 1, Value = 2)

The syntax is detailed in Constructors (F#) under the section " Assigning Values to Properties at Initialization ".

Yes, F# support use cases similar to C# object initializers but F# approach is somewhat more generic. F# specification 14.4 Method Application Resolution says:

(after method is successfully resolved) Build the resulting elaborated expression by following these steps:

  • For each NamedActualArgs whose target is a settable property or field, assign the value into the property.

meaning that you can do things that C# doesn't allow

type Something() = 
    member val Key = 0 with get,set
    member val Value = "" with get,set
    static member Create() = Something()

let a = Something(Key = 1, Value = "1") // create instance with constructor, set properties afterwards
let b = Something.Create(Key = 1, Value = "1") // create instance using factory method, set properties afterwards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM