Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are Polymorphic methods in Scala?

Dian Us Suqlain

In this shot, we’ll learn about Polymorphism and look at some polymorphic methods in Scala.

Polymorphism is the ability of any data to be processed in more than one form. In Scala, we can implement this technique through:

  • Virtual functions - These allow us to create a list of base class pointers and call methods of any of the derived classes without knowing the kind of derived class object.

  • Overloaded functions - Function overloading occurs when multiple functions have the same name, but different parameters. This is done by modifying the number of arguments and/or changing the type of arguments.

  • Overloaded operators - To perform operations that are not possible for operators in their normal form, we can overload them and use them in the program as we like.

For example, we can use the + operator to add two or more integers or floating points. To do this for two strings, however, we have to overload this operator.


We can use both values and types to parameterize Scala methods.

Value parameters are enclosed within parentheses, while type parameters are placed in brackets.


Below is an example where we use the same method def func() with different parameters:

object Main	{
	def main(args: Array[String]) : Unit = {
		var obj = new PolymorphicScala()

		println("Polymorphic Methods in Scala")

		obj.func(500, 15)
		obj.func(37.5f, 2.4f, 9.0f)

class PolymorphicScala {
	def func(a:Float) : Unit = { }
	def func(a:Float, b:Float) : Unit = {
		var div = a / b
		println("Division: " + div)
	def func(a:Float, b:Float, c:Float) : Unit = {
		var add = a * b * c
		println("Addition: " + add)
Same method but different parameters - polymorphism

In above code snippet, we declare the function func() with a float type parameter a. We can perform two operations – addition and division, for example – by changing the parameters inside the function func().

This is a classical example of function overloading.




Dian Us Suqlain
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring