Search code examples
genericsinterfacef#equality

Why does this interface implementation in F# not compile?


I am trying to implement IEquatable<T> for a particular class in F#. However, when doing so in this particular, I get an unexpected error.

I have the following code:

type Foo private (name : string) = 

member this.Name = name

member this.Equals (other : Foo) = this.Name = other.Name

override this.Equals other =
    match other with | :? Foo as foo -> this.Equals foo | _ -> false

override this.GetHashCode () = this.Name.GetHashCode ()

interface IEquatable<Foo> with
    this.Equals other = this.Equals other

This does not compile. I get the following error: "Unexpected keyword 'with' in member definition'. Also, I get a "Possible incorrect indentation ..." warning. I'm not sure what the issue is, as it appears to me that the above is how interfaces generally are implemented in F#. Why does the above not compile?


Solution

  • Well, I can answer the question myself. I didn't put member in front of the implementation. Exchanging

    this.Equals other = this.Equals other
    

    with

    member this.Equals other = this.Equals other
    

    makes everything alright. The fact that the compiler outlined the "with" keyword as the issue threw me off.