Bram
Bram

Reputation: 628

extending an object with an interface through an object expression

Is it possible to decorate an object in F# with an interface using an object expression. E.g.:

type IFoo = abstract member foo : string
type IBar = abstract member bar : string
let a = { new IFoo with member x.foo = "foo" }

/// Looking for a variation on the below that does compile, the below doesn't
let b = { a with
             interface IBar with
                 member x.Bar = "bar" }

Upvotes: 6

Views: 178

Answers (1)

Daniel
Daniel

Reputation: 47914

You can't extend an object with an interface at run-time, but you could wrap it with another object:

let makeB (a: IFoo) = 
    { 
        new IFoo with
            member x.foo = a.foo
        interface IBar with
            member x.bar = "bar" 
    }


let a = { new IFoo with member x.foo = "foo" }
let b = makeB a

Upvotes: 4

Related Questions