During refactoring of some code, I noticed a situation where code breaks when moved around:
type ThingBase () = class end
and Functions =
static member Create<'T when 'T :> ThingBase and 'T : (new : Unit -> 'T)> () = new 'T ()
and Thing () =
inherit ThingBase ()
static member Create () = Functions.Create<Thing> ()
// This works, but try moving the Functions type here instead.
If you move the Functions type below the Thing type, the code breaks unexpectedly:
type ThingBase () = class end
and Thing () =
inherit ThingBase ()
static member Create () = Functions.Create<Thing> ()
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
// This construct causes code to be less generic than indicated by the
// type annotations. The type variable 'T has been constrained to be
// type 'Thing'.
and Functions =
static member Create<'T when 'T :> ThingBase and 'T : (new : Unit -> 'T)> () = new 'T ()
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// The type ''T' does not match the type 'Thing'.
And no matter what I try, I cannot get this to typecheck. Why is the type inference so stubborn and refusing to generalize the Create method.
By the way, I also attempted F# 4.1 module rec and it also doesn't matter if Create is a function in a module either.
Any insights? To me it seems this should be something the compiler shouldn't have any troubles with.