I’m learning F# and would like to implement ThreadStatic singleton. I’m using what I found in a similar question: F# How to implement Singleton Pattern (syntax)
With the following code compiler complains that The type 'MySingleton' does not have 'null' as a proper value.
type MySingleton =
private new () = {}
[<ThreadStatic>] [<DefaultValue>] static val mutable private instance:MySingleton
static member Instance =
match MySingleton.instance with
| null -> MySingleton.instance <- new MySingleton()
| _ -> ()
MySingleton.instance
How could I initialize the instance in this scenario?
I think
[<ThreadStatic>]leads to rather clunky code, especially in F#. There are ways to do this more concisely, for example, usingThreadLocal: