Search code examples
f#f#-3.0upcasting

F# upcasting base


I get a parse error when I want to upcast base to the appropriate interface type (i.e. A) such that I can call doA() on it. I'm aware that base (http://cs.hubfs.net/topic/None/58670) is somewhat special, but I've not been able to find a work around for this particular issue thus far.

Any suggestions?

type A =
    abstract member doA : unit -> string

type ConcreteA() =
    interface A with
        member this.doA() = "a"

type ExtA() = 
    inherit ConcreteA()


interface A with
    override this.doA() = "ex" // + (base :> A).doA() -> parse error (unexpected symbol ':>' in expression)

((new ExtA()) :> A).doA() // output: ex

The working C# equivalent:

public interface A
{
    string doA();
}

public class ConcreteA : A {
    public virtual string doA() { return "a"; }
}

public class ExtA : ConcreteA {
    public override string doA() { return "ex" + base.doA(); }
}

new ExtA().doA(); // output: exa

Solution

  • This is the equivalent of your C#:

    type A =
        abstract member doA : unit -> string
    
    type ConcreteA() =
        abstract doA : unit -> string
        default this.doA() = "a"
        interface A with
            member this.doA() = this.doA()
    
    type ExtA() = 
        inherit ConcreteA()
        override this.doA() = "ex" + base.doA()
    
    ExtA().doA() // output: exa
    

    base can't be used standalone, only for member access (thus the parse error). See Specifying Inheritance, under Classes on MSDN.