Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extending an object with an interface through an object expression

Tags:

f#

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" }
like image 628
Bram Avatar asked Jul 08 '14 21:07

Bram


People also ask

Can an object extend an interface?

A Java Interface does not extend the java. lang. Object class but instances of objects that implement the interface extend the Object class otherwise if Java Interfaces allowed to extend the java.

How do you extend an interface?

An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

Which operator is used for extending interface?

Interfaces can be extended like classes using the extends operator. Note: The class implementing the interface must declare all methods in the interface with a compatible signature.

What happens when you extend an interface?

An interface is a contract without implementations (Java8 introduced default methods). By extending you extend the contract with new "names" to be implemented by concrete class.


1 Answers

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
like image 78
Daniel Avatar answered Oct 21 '22 07:10

Daniel