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, using ThreadLocal
:
open System.Threading
type MySingleton private () =
static let instance = new ThreadLocal<_>(fun () -> MySingleton())
static member Instance = instance.Value
Another F#y solution would be to store instance as an option
type MySingleton =
private new () = {}
[<ThreadStatic>; <DefaultValue>]
static val mutable private instance:Option<MySingleton>
static member Instance =
match MySingleton.instance with
| None -> MySingleton.instance <- Some(new MySingleton())
| _ -> ()
MySingleton.instance.Value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With