Interfaces contain abstract behavior for classes. It contains abstract methods. It is used to implement an inheritance hierarchy in Object-Oriented classes.

The class implements interfaces and provides an implementation for all abstract methods.

How to declare an interface in F#?

The interface contains members and abstract methods.

The abstract method only contains headers and nobody. The header contains arguments and return types with the abstract keyword.

Syntax

type interface-name = 
    [interface] [Interface-base with]
        datatype property { get; set; }
        abstract methods: arguments -> return-type
end

Interface and Interface-base with are optional, These are included during the implementation of an interface.

The interface contains properties that contain set and get variations.

How to implement an interface in F

Let’s declare an Animal interface that contains a getName abstract member the interface implements another interface example

type Animal =  
   abstract member getName : unit -> unit  

Create a Dog class implements an Animal interface, and provides an implementation for an abstract method in a class.

type Dog( name:string) =  
   interface Animal with  
      member this.getName() = printfn "\nName = %s" name  

Next, how to create interface members or methods?

Create an Object of a class that implements an interface. Call method members using object :> interface syntax.

let dog = new Dog("dog")  
(dog :> Animal).getName()  

How to access property members of an interface in Interface

Interfaces can contain property members. In method members, You can call properties by casting self-interface.

Here is an example

type Animal() = 
    interface Lion with
        member val name = "lion" with get, set
        member self.getName() = if (self :> Lion).name then () else ()