真・懒

订阅 Twitter GitHub 联系

Load once with lazy

In ObjC, +load or +initiliaze of NSObject is a nice place to put some code that executes only once, e.g. register some dependency injections.

There is no such concept in F#, but can be archived with the lazy expressions:

module Service =
  let private _getDef = lazy (
    DicService.registerHttpMessageHandler (new NSUrlSessionHandler ())
    (fun word -> DicService.getDefinition word platformSpecFunc))

  let getDef = _getDef.Force()

By using lazy, our _getDef will execute at the first time when getDef being called, and only once.