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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With