When does an F# type need to be initialised using new?

家住魔仙堡 提交于 2019-12-07 00:28:39

问题


Given a class such as:

type MyClass() =
    member this.Greet(x) = printfn "Hello %s" x

is it appropriate to initialize instances using

let x = new MyClass()

or without the new?

Also, when is the use of a new constructor more useful than a do binding with parameters supplied to the type definition?


回答1:


My pattern in F# for using new is to only do so when the type implements IDisposable. The compiler special cases this use and emits a warning if new is omitted.

So in your case I would not use new. But with the following I would

type OtherClass() =
  ...
  interface System.IDisposable with 
    member this.Dispose() = ...

let x = new OtherClass()



回答2:


F# spec:

68 6.5.2 Object Construction Expressions An expression of the form new ty(e1 ... en) is an object construction expression and constructs a new instance of a type, usually by calling a constructor method on the type.

14.2.2 Item-Qualified Lookup The object construction ty(expr) is processed as an object constructor call as if it had been written new ty(expr).

F# compiler issues a warning if instance of type that implements IDisposable is created with Ty() syntax omitting new keyword. Spec says nothing about this fact, however I think it should definity should be mentioned.



来源:https://stackoverflow.com/questions/3398916/when-does-an-f-type-need-to-be-initialised-using-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!