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?
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 ()
}