Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Implement an interface in F#

Tags:

f#

I have an interface in C# like this:

public interface IMessageOptions
{
    int ReceiveTimeout { get; set; }
    int PeekTimeout { get; set; }
    bool Transactional { get; set; }
}

and I'm trying to implement it in F# like this:

type Settings() =
    interface IMessageOptions with
        member this.PeekTimeout: int with get, set
        member this.ReceiveTimeout: int with get, set // error at start of this line
        member this.Transactional: bool with get, set

But I get an error after the first property saying:

"Incomplete structured construct at or before this point in pattern"

How should this be written?

Are auto properties not allowed in this context?

like image 455
reckface Avatar asked Jan 11 '16 10:01

reckface


People also ask

How do you implement an interface?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

What is an interface in functional programming?

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods.

Can we do implementation in interface?

An interface can extend any number of interfaces but one interface cannot implement another interface, because if any interface is implemented then its methods must be defined and interface never has the definition of any method.


2 Answers

Here is the syntax for that:

type Settings() =
   interface IMessageOptions with
      member val PeekTimeout = 0 with get, set
      member val ReceiveTimeout = 0 with get, set
      member val Transactional = false with get, set

The differences are:

  • Use val instead of this.
  • Define the default values explicitly
  • You don't have to specify the types (although you can)

For the reference, here is how you would define the interface itself in F#:

type IMessageOptions =
  abstract member PeekTimeout : int with get, set
  abstract member ReceiveTimeout : int with get, set
  abstract member Transactional : bool with get, set
like image 101
Mikhail Shilkov Avatar answered Nov 15 '22 12:11

Mikhail Shilkov


If you want automatically implemented properties, then this is the syntax:

type Settings() =
    interface IMessageOptions with
        member val PeekTimeout : int = 0 with get, set
        member val ReceiveTimeout : int = 0 with get, set
        member val Transactional : bool = false with get, set

Notice that you explicitly have to define the default value.

like image 43
Mark Seemann Avatar answered Nov 15 '22 11:11

Mark Seemann