githubEdit

Interface

Syntax

Similar to an abstract class but with only abstract members.

Atttribute:

  • [<AbstractClass>] attribute can not be used to declare an interface

  • [<Interface>] attribute is optional but recommended in most cases

type [accessibility-modifier] interface-name =
    abstract memberN : [ argument-typesN -> ] return-typeN
  • Interface name begins with I to follow the .NET convention

  • Arguments can be named (without parentheses otherwise 💥)

[<Interface>]
type IPrintable =
    abstract member Print : format: string -> unit

You can also use verbose syntax with an interface ... end block. → Not idiomatic except in the case of a member-less interface a.k.a marker interface.

type IMarker = interface end

Implementation

2 ways of implementing an interface:

  1. In an object expression 📍

  2. In a type (as in C♯)

circle-exclamation

Keyword

Default implementation

F♯ 5.0 supports interfaces defining methods with default implementations written in C♯ 8+ but does not allow them to be defined directly in F♯.

circle-exclamation

Keyword

F♯ interface is explicit

F♯ interface implementation ≡ Explicit implementation of an interface in C♯

→ Interface methods are accessible only by upcasting:

Implementing a generic interface

Inheritance

Defined with the inherit keyword

Last updated