Alex 75
Alex 75

Reputation: 3236

F# call member function from another function of a type when implement interface

This is the working example from here:

type MethodExample() = 

    // standalone method
    member this.AddOne x = 
        x + 1

    // calls another method
    member this.AddTwo x = 
        this.AddOne x |> this.AddOne

That is what I want to do:

type IMethod =   
    abstract member  AddOne: a:int -> int
    abstract member  AddTwo: a:int -> int

type MethodExample() =     
    interface IMethod with

        member this.AddOne x = 
            x + 1

        // calls another method
        member this.AddTwo x = 
            this.AddOne x |> this.AddOne

The AddOne function is not available, I also tried to downcast this to MethodExample but is horrible and does not work.

How can I do it?

Upvotes: 4

Views: 1213

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

In F# all interface implementations are private - meaning interface methods do not also appear as public methods of the class, like they do in C#. They are only accessible via the interface.

Therefore, in order to access them, you need to cast your class to the interface first:

member this.AddTwo x = 
    let me = this :> IMethod
    me.AddOne x |> me.AddOne

Upvotes: 9

Related Questions