FSharp.Json icon indicating copy to clipboard operation
FSharp.Json copied to clipboard

Specifying Default Values As Compile Time Constants

Open Evelios opened this issue 4 years ago • 0 comments

From the JsonConfig Documentation it specifies how default values in types should be used. I am trying to be able to get the record to be populated

type MyType= {
      [<JsonField(DefaultValue ="">]  // Works
      asString: string

      [<JsonField(DefaultValue =[||])>]  // Run time error
      asArray: int[]

      [<JsonField(DefaultValue = [])>]  // Compile Time Error
      asList: int list}

I'm assuming this code is used inside the reflexive record value code. Pulling in the default value to the JsonField so that it is able to give it a default value that way. So the JsonField is being created in the library code.

Giving it in this format requires this value to be a compile time constant. "" is a compile time constant, and so is [||] but [] isn't.

Running it in the array [||] example, I get the following run time error

System.ArgumentException : Object of type 'System.Object[]' cannot be converted to type 'System.Int32[]'.

Trying to build in the example with the list I get the following compile time error

[FS0267] This is not a valid constant expression or custom attribute value

I also can't use the Array.empty and List.empty values, because those are also not compile time constants.

I don't know if there is another recommended way of setting defaults that doesn't have this requirement, but I don't see a way of getting around this issue other the letting list values be optional, allowing for the null case, which is not optimal.

Evelios avatar Mar 18 '21 20:03 Evelios