Wednesday, December 18, 2013

Polymorphism in Scala

Is Scala polymorphic? Incase yes, what are the different ways with which this is supported?

Scala being a hybrid of object & functional programming paradigmn, supports polymorphism. Scala support two polymorphism forms:

Subtyping: 

Instances of subclass can be passed to functions instead of declared base class.

Generics:

Functions and classed driven via type parameterization.
  1. Function can be applied to arguments of many types (via generics support at method level)
  2. The type can have instance of many types (via generics support at class level)
Field definition in Scala are special cases of method overriding. They can implement abstract method overriding and traits.

Below are a few highlights in the example:
  1. Cons(val head: Int, val tail: IntList) declares both parameter and field of the class. By declaring this it automatically overrides the abstract definition for head and tail methods.
  2. Generic Type parameter using [T] similar to type definition in Java via <T>
  3. Type parameters are not just limited to classes, but they can be declared at method level as well.
Since Nothing is a subtype of any other type and this is true for T as well. Therefore below syntax is valid and there by this method can be overrided with below definition
def head: Nothing = throw new NoSuchElementException("head.nil")
def tail: Nothing = throw new NoSuchElementException("tail.nil")

No comments:

Post a Comment