Interface conflict addressing in F #

I would like to implement the solution described here in F #: Inheriting from multiple interfaces with the same method name

In particular, in F #, how do I address interface implementation functions that have the same name between two interfaces?

Here is the C # solution:

public interface ITest {
    void Test();
}
public interface ITest2 {
    void Test();
}
public class Dual : ITest, ITest2
{
    void ITest.Test() {
        Console.WriteLine("ITest.Test");
    }
    void ITest2.Test() {
        Console.WriteLine("ITest2.Test");
    }
}
+6
source share
1 answer

In F #, interfaces are always implemented explicitly, so this is not even a problem that needs to be solved. So you would implement these interfaces regardless of whether the method names were the same:

type ITest =
    abstract member Test : unit -> unit

type ITest2 =
    abstract member Test : unit -> unit

type Dual() =
    interface ITest with
        member __.Test() = Console.WriteLine("ITest.Test")

    interface ITest2 with
        member __.Test() = Console.WriteLine("ITest2.Test")

, , F # . Dual, Test. ITest ITest2:

let func (d:Dual) = d.Test() // Compile error!

let func (d:Dual) =
    (d :> ITest).Test()
    (d :> ITest2).Test()
    // This is fine

, upcast :> , , , .

, , , .

+11

All Articles