Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

f#

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?

like image 544
Alex 75 Avatar asked Oct 15 '25 13:10

Alex 75


1 Answers

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
like image 88
Fyodor Soikin Avatar answered Oct 18 '25 18:10

Fyodor Soikin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!