How can you achieve polymorphism in Scala?

Instruction: Discuss different ways to achieve polymorphism in Scala, providing examples for each.

Context: This question assesses subtype, parametric and ad-hoc polymorphism in Scala, including dynamic dispatch and contextual type-class instances.

Updated

Scala supports several forms of polymorphism. Subtyping lets a common interface dispatch to different implementations; parametric polymorphism writes one implementation over a type parameter; type classes select behavior through contextual instances.

trait Shape { def label: String }
class Circle extends Shape { def label: String = "circle" }
class Square extends Shape { def label: String = "square" }
def label(shape: Shape): String = shape.label
def same[A](value: A): A = value

trait Encode[A] { def apply(value: A): String }
object Encode {
  given Encode[Int] with { def apply(value: Int): String = s"int:$value" }
  given Encode[String] with { def apply(value: String): String = s"text:$value" }
}
def encode[A](value: A)(using e: Encode[A]): String = e(value)

@main def polymorphismExample(): Unit = {
  assert(List[Shape](new Circle, new Square).map(label)
    == List("circle", "square"))
  assert(same(3) == 3 && same("x") == "x")
  assert(encode(3) == "int:3" && encode("x") == "text:x")
}

The shape implementation is selected through dynamic dispatch. same requires no operation on its unknown element type. encode requests a capability for that type; companion instances are found through contextual resolution. Type classes can add behavior without changing a domain class's inheritance hierarchy. Polymorphic methods Implementing type classes

Overloading is another form of ad-hoc polymorphism, with alternatives selected from static argument information. These techniques solve different design problems. Inheritance can provide a simple shared contract; type classes can support retroactive or alternative behavior but introduce resolution and discoverability concerns. None automatically guarantees extensibility, correctness or superior performance.

Related Questions