Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Explicit Interface Method for Two Interfaces

What is the correct way to handle this situation. I have one method in my F# class DogTree that should fulfill the requirement of implementing a Bark() method for both interfaces.

type ITree =
    interface
        abstract Bark : unit -> unit
        abstract Grow : unit -> unit
    end

type IDog =
    interface
        abstract Bark : unit -> unit
        abstract ChaseCar : unit -> unit
    end

type TreeDog = 
   // so the "and" syntax below doesn't work - what is the correct way to handle?
   interface IDog and ITree with
      member this.Bark() = printfn "Bark" 
like image 557
BuddyJoe Avatar asked May 05 '26 21:05

BuddyJoe


2 Answers

You can delegate to a common implementation:

type TreeDog = 
  interface IDog with
    member this.Bark() = printfn "Bark" 
  interface ITree with
    member this.Bark() = (this :> IDog).Bark()

Or, more appropriately:

type TreeDog = 
  member this.Bark() = printfn "Bark"
  interface IDog with
    member this.Bark() = this.Bark() 
  interface ITree with
    member this.Bark() = this.Bark()

(Note that this defines an extra method in the class named Bark, that is used as the implementation for both interfaces.)

If you declare a primary constructor in your class, you can use this instead:

type TreeDog() = // primary constructor
  let bark() = printfn "Bark" // this member is private
  interface IDog with
    member this.Bark() = bark()
  interface ITree with
    member this.Bark() = bark()
like image 94
Jordão Avatar answered May 08 '26 13:05

Jordão


This is reasonably elegant

type TreeDog() = 
  let bark() = printfn "Bark" 
  interface IDog with
    member this.Bark() = bark()
  interface ITree with
    member this.Bark() = bark()
like image 28
John Palmer Avatar answered May 08 '26 14:05

John Palmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!