You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo


So far in object-oriented programming, we have modeled a couple of different relationships. Is a relationships can be modeled through inheritance, and has a relationships are modeled through aggregation (fields and properties). For example, a BMW is a car (inherits from type Car) and has a motor (contains a field named m_motor of type Engine).

There is, however, a third type of relationship, the can do relationship, which means that type X can do the operations described by type Y. For example, people, cars, and wine all age. While there may be no clear relationship between people, cars, and wine, they are all capable of aging.

In .NET programming, the can do relationship is modeled via an interface, which is a contract that a type can implement to establish that it can perform a certain set of actions.

An interface is just a collection of methods and properties. A type can declare that it implements the interface if it provides an implementation for each method or property. Once this contract has been implemented, then the type can do whatever the interface describes.

In Example 6-1, several types implement the IConsumable interface. To implement an interface, use the interface keyword followed by the implementation of each interface method or property to fulfill the contract. If a class implements the IConsumable interface, it means that the class has a Tastiness property and an Eat method.

Example 6-1. Interfaces in F#

type Tastiness = | Delicious | SoSo | TrySomethingElse ...

The best content for your career. Discover unlimited learning on demand for around $1/day.