How does Scala achieve 'Static Polymorphism'?

Instruction: Discuss the mechanisms Scala uses to implement static polymorphism and provide an example.

Context: This question aims to evaluate the candidate's knowledge on how Scala implements compile-time polymorphism, primarily through method overloading, and how it benefits code flexibility and readability.

Updated

Method overloading is commonly called static or ad-hoc polymorphism: the compiler chooses a method signature from the argument types available at the call site. Generic methods provide parametric polymorphism by expressing behavior for a type parameter. Neither mechanism means that all calls on an object are resolved statically.

def identify(value: Any): String = "Any overload"
def identify(value: String): String = "String overload"
def identity[A](value: A): A = value

class Base { def label: String = "base" }
class Child extends Base { override def label: String = "child" }

@main def polymorphismExample(): Unit = {
  val text: String = "hello"
  val widened: Any = text
  assert(identify(text) == "String overload")
  assert(identify(widened) == "Any overload")
  assert(identity(7) == 7)
  val instance: Base = new Child
  assert(instance.label == "child")
}

The runtime object stored in widened is still a string, but its static type selects the Any overload. By contrast, overriding label uses dynamic dispatch to the child's implementation. Type-class context parameters are another way to select operations for a generic type while keeping required capabilities explicit. Polymorphic methods Overload resolution

Overloads must be distinguishable to the compiler and compatible with JVM signature rules; return type alone does not distinguish otherwise identical parameter lists. A generic arithmetic method also needs an appropriate capability, such as Numeric[A], rather than assuming every type supports addition. These choices support API expressiveness but do not establish a performance advantage without measurement.

Related Questions