Interface in Verse
The interface type provides a contract for how to interact with any class that implements the interface. An interface cannot be instantiated, but a class can inherit from the interface and implement its methods. An interface is similar to an abstract class, except that it does not allow partial implementation or fields as part of the definition.
For example, let’s create an interface for anything that you can ride on, such as a bicycle or a horse:
Verse
| | |
| --- | --- |
| | rideable := interface(): |
| | Mount()<decides> : void |
| | Dismount()<decides> : void |
rideable := interface(): Mount()<decides> : void Dismount()<decides> : void
Copy full snippet(3 lines long)
Any classes that inherit the interface must implement the interface’s functions and add the override specifier:
Verse
bicycle := class(rideable):
...
Mount<override>()<decides> : void =
...
Dismount<override>()<decides> : void =
...
horse := class(rideable):
...
Mount<override>()<decides> : void =
Expand code Copy full snippet(13 lines long)
An interface can extend another interface. For example, you can specify that anything that you can ride should also be able to move.
Verse
| | |
| --- | --- |
| | moveable := interface(): |
| | MoveForward() : void |
| | |
| | rideable := interface(moveable): |
| | Mount()<decides> : void |
| | Dismount()<decides> : void |
moveable := interface(): MoveForward() : void rideable := interface(moveable): Mount()<decides> : void Dismount()<decides> : void
Copy full snippet(6 lines long)
A class can inherit from an interface and another class. For example, you can define a horse, and differentiate it from one that has a saddle you can ride on:
Verse
horse := class(moveable):
...
MoveForward()<decides> : void =
...
saddle_horse := class(horse, rideable):
...
Mount<override>()<decides> : void =
...
Dismount<override>()<decides> : void =
Expand code Copy full snippet(11 lines long)
A class can inherit from multiple interfaces.
Verse
lockable := interface():
Lock() : void =
...
Unlock() : void =
...
bicycle := class(rideable, lockable):
…
Mount<override>()<decides> : void =
...
Expand code Copy full snippet(18 lines long)