Explicit type parameters in binding methods in classes

When I try to create some class like

type MyType () = let func<'T> () = () 

The compiler says that there is an error:

Explicit type parameters can only be used for binding modules or elements

But MSDN says:

Let the binding at the module level, in a type or in a calculation expression, have explicit type parameters. The let binding in an expression, for example, in a function definition, cannot have type parameters.

Why do documentation and compiler say different things?

+7
source share
2 answers

This is apparently the syntactic restriction on let binding inside the class. However, you can still define a common local function, you just need to specify the type parameters in the type annotations:

 type MyType () = let func (x : 'T) : 'T = x 

I do not think this is explicitly syntactically forbidden by the specification, because the specification states that the class definition has the following structure:

type type-name patopt as-defnopt =
class inherits-Decl <sub> non-automatic sub>
Class-function or-valuation defns <sub> non-automaticSub>
Defn type

and class-or-value-defn is defined as:

class-function-or-value-defn: = attributes opt static opt let rec opt function- or cost, defns

where function-or-value-defns can be a function definition with explicit parameters of the type:

function-defn: =
inline opt access opt ident-or-op typar-defns opt argument-pats return-typeopt = expr

+5
source

To add Tomas to the answer, if you need a type parameter, but will not have a value for that type, you can use a type with a phantom type parameter. eg:.

 open System type Foo() = member x.PrintType<'T> () = printfn "%s" typeof<'T>.Name type TypeParameter<'a> = TP let foo = Foo () let callFoo (typeParameter : TypeParameter<'a>) = foo.PrintType<'a> () callFoo (TP : TypeParameter<string>) callFoo (TP : TypeParameter<DateTime>) 
+2
source

All Articles