Polymorphism in Scala

Polymorphism is a fundamental concept in object-oriented programming, and Scala supports both compile-time and runtime polymorphism. Here's a brief overview of polymorphism in Scala:

1. Compile-time polymorphism: Compile-time polymorphism in Scala is achieved through method overloading and default parameter values. Method overloading allows you to define multiple methods with the same name but different parameters. Default parameter values allow you to define methods with optional parameters that can be omitted when the method is called. Here's an example:

   

class MathUtils {
def square(x: Int): Int = {
x * x
}
def multiply(x: Int, y: Int = 1): Int = {
x * y
}
}
val mathUtils = new MathUtils()
println(mathUtils.square(3)) // prints 9
println(mathUtils.multiply(3)) // prints 3
println(mathUtils.multiply(3, 4)) // prints 12


`

In this example, “MathUtils” is a class that defines two methods: “square” and “multiply”. “square” takes a single integer parameter and returns its square, while “multiply” takes two integer parameters and returns their product. The second parameter of “multiply” has a default value of 1, so it can be omitted when the method is called.

2. Runtime polymorphism: Runtime polymorphism in Scala is achieved throughmethod overriding and inheritance. Method overriding allows a subclass to provide its own implementation of a method defined in its superclass. This allows a subclass to modify or extend the behavior of the superclass method. Here’s an example:


`
class Animal {
def makeSound(): Unit = {
println(“The animal makes a sound”)
}
}
class Dog extends Animal {
override def makeSound(): Unit = {
println(“The dog barks”)
}
}
val animal: Animal = new Dog()
animal.makeSound() // prints “The dog barks”


`

In this example, “Animal” is a superclass that defines a method “makeSound”, and “Dog” is a subclass that overrides the “makeSound” method with its own implementation. We create an instance of “Dog” and assign it to a variable of type “Animal”, which allows us to call the “makeSound” method on it. When we call “makeSound”, the implementation provided by “Dog” is executed instead of the implementation provided by “Animal”.

Overall, Scala provides both compile-time and runtime polymorphism, which allows you to write flexible and extensible code. Compile-time polymorphism can be achieved through method overloading and default parameter values, while runtime polymorphism can be achieved through method overriding and inheritance.