Why doesn’t the following code compile? Is that a compiler bug or a language feature? What is the best workaround?
type A() as this =
let a = this.GetTypedObject<int>() // a
let b = this.GetTypedObject<string>() // b
member this.GetTypedObject<'T>() =
Unchecked.defaultof<'T>
Unchecked.defaultof<‘T> is used for example only, any function or constructor call could be used instead.
Compiler says that code becomes less generic at line (a) and refuses to compile line (b).
I cannot give exact compiler messages because I have them in Russian :).
Turning method GetTypedObject() into a let binding and removing <‘T> ends up with another compiler warning which I don’t like either. The only wokaround I found is to move GetTypedObject<‘T>() into a base class and to make it public. Thanks in advance…
Since type inference works top-to-bottom,
it encounters. (As Brian points out, members are read prior toGetTypedObjectreturningintbefore it even reaches the method definition and discovers it should be genericletbindings…and there’s a simpler fix for this.) I get the following nasty error:If the usage appears after the method definition, it works.
Here’s a workaround: