Object reference in interface part of object expression

60 Views Asked by At

I'm trying to override an interface for a class in an object expression, but having trouble accessing the 'this' reference for the class I'm subclassing.

Example:

type IFoo =
    abstract member DoIt: unit -> unit

type Foo () =
    member x.SayHey () = printfn "Hey!"
    member x.SayBye () = printfn "Bye!"
    interface IFoo with
        member x.DoIt () = x.SayHey () // x is 'Foo'


let foo =
   {
     new Foo () with
        // Dummy since F# won't allow object expression with no overrides / abstract implementations
        override x.ToString () = base.ToString () 
     interface IFoo with
        member x.DoIt () = x.SayBye () // Error: x is 'IFoo'
   }

Bonus question: Can I somehow get rid of that dummy override?

2

There are 2 best solutions below

3
robkuz On BEST ANSWER

You have to cast your access in IFoo so that

let foo =
    {
         new Foo () with
             override x.ToString () = base.ToString () 
         interface IFoo with
             member x.DoIt () = (x :?> Foo).SayBye () 
    }
1
rmunn On

Cast your x in the IFoo interface to the Foo type:

let foo =
{
    new Foo () with
        // Dummy since F# won't allow object expression with no overrides / abstract implementations
        override x.ToString () = base.ToString () 
    interface IFoo with
        member x.DoIt () = (x :?> Foo).SayBye () // No type error
}

Related Questions in F#