M.Y. Babt
M.Y. Babt

Reputation: 2891

F#: Saving JSON data

I am new to programming and F# is my first language.

Here are the relevant parts of my code:

let internal saveJsonToFile<'t> (someObject:'t) (filePath: string) =  
    use fileStream = new FileStream(filePath, FileMode.OpenOrCreate) 
    (new DataContractJsonSerializer(typeof<'t>)).WriteObject(fileStream, someObject)

let testList = new List<Fighter>()

saveJsonToFile testList<Fighter> @"G:\User\Fighters.json"

I have previously created an F# record of type Fighter.

When I try to run "saveJsonToFile testList @"G:\User\Fighters.json"", "testList" is underscored in red with the error message: "Unexpected type arguments".

What went wrong? What am I missing?

Upvotes: 0

Views: 615

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80734

First, your testList is a value, not a function.
Second, it doesn't have a generic argument, everything in its body is concrete.

If you want it to be a function, give it a parameter.
If you want it to be generic, say so in the body.

let testList () = new List<'a>()
saveJsonToFile testList<Fighter>() @"G:\User\Fighters.json"

And finally, the List you're trying to create probably resolves to F#'s own List, which is a module, not a type.
If you meant to create the .NET's System.Collections.Generic.List, then you need to specify the full type name:

let testList () = new System.Collections.Generic.List<'a>()

But if you meant to create an F# native list, use one of its constructors:

let testList () = []

Upvotes: 1

Related Questions