views:

145

answers:

2

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?

+7  A: 

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()
JaredPar
I wonder why this came about. Wouldn't it be clear by using the `use` keyword?
ChaosPandion
@ChaosPandion, no idea really. I'm sure Brian will be along shortly to provide the full history
JaredPar
@ChaosPandion: there are circumstances where you don't want to create a new IDisposable with a use binding, like when you want it to escape the function that creates it.
Alex Humphrey
I almost always say `new`. I think if you have a function with the same name as a class, then you need `new` to disambiguate. I don't know of any style guideline here.
Brian
@Brian, why does the F# compiler chose to enforce this specific case?
JaredPar
I don't know; will ask.
Brian
@Brian: Interesting. The reason I am leaning towards not using `new` is precisely to have the ambiguity between class creation and having a function that returns instances (possibly as a factory). This kind of ambiguity looks to me similar in some sense to the ambiguity profitably used in a name that can be imported from multiple namespaces or modules. Is there anything wrong with that?
Muhammad Alkarouri
Sure, if you want to do `type Foo() = ...` followed by `let Foo() = new Foo()` as a protective abstraction, that's fine.
Brian
+3  A: 

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.

desco