just me
just me

Reputation: 73

Overriding an inherited member in F#

The code below produces "t1 t1 t2". I wondered if someone could please tell me how to change it so as to get "t1 t2 t2". It is an error to use "override" instead of "member" in t2, and I don't understand why. I am more than happy to RTFM, if only I would know where and in what FM to look.

Many thanks in advance, and sorry if I missed some fundamental reason for why what I want should not be possible.

type myinterface =
   abstract member doit : unit -> unit

type t1 () =
   interface myinterface with
      member x.doit () = printf "t1\n"

type t2 () =
    inherit t1 ()

    member x.doit () = printf "t2\n"

let override_test () =
    let t1 = t1 () :> myinterface
    let t2 = t2 ()
    let t2i = t2 :> myinterface
    t1.doit ()
    t2i.doit ()
    t2.doit ()

Upvotes: 5

Views: 2118

Answers (1)

ildjarn
ildjarn

Reputation: 62975

This should have the behavior you want:

type myinterface =
    abstract member doit : unit -> unit

type T1 () =
    interface myinterface with
        member x.doit () = printfn "t1"

type T2 () =
    inherit T1 ()
    member x.doit () = printfn "t2"
    interface myinterface with
        member x.doit () = x.doit ()

let override_test () =
    let t1i = T1() :> myinterface
    let t2 = T2()
    let t2i = t2 :> myinterface
    t1i.doit ()
    t2i.doit ()
    t2.doit ()

Upvotes: 7

Related Questions