Search code examples
propertiesf#nullablerecords

Optional parameters in Fsharp records


I need to modify and add new property for my F Sharp record. but then it gives errors for the previous instances which are made without this new field. I made it as Nullable ,but still the same error occures, Please help me to solve this


Solution

  • I presume you mean "optional" as in "a field that I don't provide when instantiating the record". However, there is no such thing as an optional field in F# records unfortunately (or fortunately, depending on your point of view). All record fields that you specify must be present at the point when you instantiate it.

    See also this closely related question.

    You may consider this trade-off:

    • Use a record. Each time you update the record, the F# compiler will scream and alert you about all places where you used this record, and you need to now provide the additional information. The additional information can be a None for the fields you added, if they are options. The big advantage: Your code itself will not have to handle all of the possibly many cases of "what to do if field1 is missing? What if field2 is missing, too?"

    • Use a class. When you update the class, the F# compiler will not enforce any sort of completeness check about the information you put into the class. (You can view records as classes where all fields are constructor arguments, and all must be provided). Hence, updating the class definition causes no overhead, but your code needs handle all the missing values.

    I personally prefer records just because it forces me to think through the implications of adding a new field.

    There is of course a middle ground: You can use records, but instantiate all of them via static members or something alike:

    type Name = 
        { 
            First: string
            Family: string
        }        
        static member Create(first, family) = { First = first; Family = family}
    

    If, in your code, you always use Name.Create to instantiate the record, you will of course be able to add a MiddleName field without any consumer code noticing.