Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

f#

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?

like image 905
rabejens Avatar asked Jun 20 '19 13:06

rabejens


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 
like image 99
Tomas Petricek Avatar answered Nov 08 '22 03:11

Tomas Petricek