Search⌘ K

Using Protocols to Create Polymorphic Functions

Explore how to create polymorphic functions using Elixir protocols. Understand defining protocols, implementing them for different structs, and improving code reuse and extensibility without modifying existing data types. This lesson guides you through building flexible display functions and organizing protocol code effectively.

Introduction to Elixir’s protocols

Elixir’s protocol is a feature that lets us create a single interface that various data types can implement. We can use this to implement polymorphism because it’s a single interface that works with different data types. If you came from object-oriented languages like Java, you’d see that it’s very similar to how interfaces work. Elixir protocols will help us create simple interfaces, leading to a better codebase design.

In this lesson, we’ll explore more about structs, including structs that reference other structs. We’ll refactor our code to create a reusable module that shares functions between heroes and action selections. Then we’ll build polymorphic functions with protocols to display heroes and actions. The first step is to define the essential attributes of the rooms and their actions.

Displaying heroes and room actions with protocols

We listed the options for the player; these options can be room actions or heroes. It means we need to work with different data ...