How to realize Polymorphism in Scala

Polymorphism is the ability to present different data types using the same interface.
We have polymorphic functions and polymorphic types.

  • A polymorphic type is one whose operations can also be applied to values of some other type, or types.
  • A polymorphic function is the one that can be applied to arguments of many types. A polymorphic function can denote the number of distinct and potentially heterogeneous implementations depending on the type of argument(s) to which it is applied.

In many programming languages, although the types of integers and floats are different and they are not considered as objects, they are considered to be implicitly polymorphic as they can be beaded, subtracted, and multiplied together.
Similarly, a class can also give those operations, despite the fact that they work on dissimilar data types.

Types of Polymorphism

There are three different kinds of polymorphism:

  • Ad hoc Polymorphism
  • Parametric Polymorphism
  • Subtyping

Ad hoc polymorphism:

If a function has dissimilar implementations, that depend on a range of specified types and combinations that are limited, we have ad hoc polymorphism. Ad-hoc polymorphism is supported in many programming languages using function overloading. It uses polymorphic functions since they can be applied to arguments of different data types.

Parametric polymorphism:

If we write the code in such a way that no specific data type is mentioned, and the said code can be used with any number of new data types, we have used parametric polymorphism. This is also known as generic programming in the Object Oriented community whereas, in the functional programming community, it is known as simply polymorphism.

Subtyping:

In subtyping, we have one common base class, and many subclasses are derived from it.

Example:

An example of polymorphism is the Shape class and all the classes that can be derived from it. First, you have to create a base class. Let’s name it “Shape.” The derived classes from it can be named as “Rectangle,” “Circle,” and “Triangle” etc. The base class “Shape” would have a function “Draw” which will be overridden in each derived class to draw the desired particular shape. You will have to create an object that would list all the shapes and add a Circle, Triangle, and Rectangle to it. By making the class responsible for its code as well as its data, you can achieve polymorphism. type.png The three types of polymorphism differ from each other in the way that the data type hierarchy is expressed explicitly using extends keyword in Scala (for subtyping) or data type parameters (for parametric polymorphism). The Ad hoc polymorphism bases itself on implicit classes to mix the behavior (using traits).

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?