Search code examples
f#type-constraints

How do I properly override a constrained method


How do I override the method Zero in the following code in such a way that I can return Euro(0) for the definiton in the type Euro

[<AbstractClass>] 
type Currency () =
    abstract member Zero<'T when 'T :> Currency > : unit -> 'T

type Euro (value: int) =
    inherit Currency()
    member this.Value = value
    override this.Zero() = Euro(0) :> _

Solution

  • Have you tried lifting the generic constraint to the class level?

    [<AbstractClass>] 
    type Currency<'T when 'T :> Currency<'T>>() =
        abstract member Zero : unit -> 'T
    
    type Euro (value: int) =
        inherit Currency<Euro>()
        member this.Value = value
        override this.Zero() = Euro(0)
    

    Though self-referencing generics always seems weird to me, this is how it'd be done in, for example, C#.