How to require multiple interfaces in F# when a parameter is an object type?

Viewed 143

In scala, I can require multiple traits like this:

def foo(bar: Foo with Bar): Unit = {
  // code
}

Is this also possible in F#, or do I have to explicitly declare a FooBar interface that inherits Foo and Bar?

1 Answers

You can specify this by having a generic type 'T with constraints that restrict 'T to types that implement the required interfaces.

For example, given the following two interfaces:

type IFoo = 
  abstract Foo : int 
type IBar = 
  abstract Bar : int 

I can write a function requiring 'T which is IFoo and also IBar:

let foo<'T when 'T :> IFoo and 'T :> IBar> (foobar:'T) = 
  foobar.Bar + foobar.Foo

Now I can create a concrete class implementing both interfaces and pass it to my foo function:

type A() = 
  interface IFoo with 
    member x.Foo = 10
  interface IBar with 
    member x.Bar = 15

foo (A()) // Type checks and returns 25 
Related