Search code examples
.netinterfacef#explicit-interfaceexplicit-implementation

Implementing Interfaces Explictly in F#


Ok, C# has Explictit Interface Implementation I'l like to do similar in F#.

I have some Interfaces (and classes)

type IState = interface
    abstract member Update : IAction-> IState
    ...
end
type IEnviroment = interface
    abstract member Update : IAction-> IEnviroment
    ...
    end


type IBoard  = 
    inherit IState
    inherit IEnviroment
    abstract member Update : Move -> IBoard
    ...

[<AbstractClass>]
and Move ()= 
    abstract member Apply : IBoard -> IBoard
    interface IAction with        
        override this.Cost = 1M

So the problem I have is that Update is defined 3 times differently. So I need the equivelent of C#'s Explictit Interface Implementation, I'me thinking I'ld implement it in the interface (since that is legit in F#) - it would just consist of some typecasts.

My understanding is that all interface implementation in F# is explcit, in classes, But once an interface inherits from another inferface, then you only (explicitly) implement that one. (so my Board class only implments I Board)


Solution

  • I tried the syntax member this.IState.Update in the implementation of IBoard, but the compiler rejected it.

    I don't see a way in the spec to do what you want.

    Here is a work-around in for such name clashes, using an abstract class to forward calls to each interface.

    type I1 =
        interface
            abstract F : unit -> unit
        end
    
    type I2 =
        interface
            abstract F : unit -> unit
        end
    
    type II =
        interface
            inherit I1
            inherit I2
            abstract F : unit -> unit
        end
    
    [<AbstractClass>]
    type III() =
        abstract F1 : unit -> unit
        abstract F2 : unit -> unit
        abstract F3 : unit -> unit
        interface I1 with
            member this.F() = this.F1()
        interface I2 with
            member this.F() = this.F2()
    
    type Works() =
        inherit III()
        override this.F1() = printfn "F1"
        override this.F2() = printfn "F2"
        override this.F3() = printfn "F3"
    
    type Fails() =
        interface II with
            member this.F() = ()