DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Scala Ad Hoc Polymorphism Explained

Scala Ad Hoc Polymorphism Explained

Scala supports several types of polymorphism. Ad hoc is perhaps the most versatile, letting you augment your types based on a given situation.

Tomer Ben David user avatar by
Tomer Ben David
·
Apr. 04, 17 · Tutorial
Like (9)
Save
Tweet
Share
25.29K Views

Join the DZone community and get the full member experience.

Join For Free

There are different types of Polymorphism, namely:

  1. Subtype Polymorphism: Remember OOP? Yes, that's the one from there.
  2. Parametric Polymorphism: Generics! With type parameters. A function or a data type will handle values with different types the same way.
  3. Ad hoc polymorphism: It's also based on generics, so it's similar to Parametric Polymorphism but with a twist (see below).

Parametric vs. Ad Hoc Polymorphism

So we have three types of polymorphism (isn't that just polymorphic? :-) ). Subtype we know from good old OOP. The difference between Parameteric and Ad Hoc is intriguing, though. They both use generics in order to allow code to run on different types. When you have Parametric polymorphism, you define some shared functionality and you have a type parameter. Now, whenever you run this code and supply the type parameter, this shared code will run with this type parameter. The difference, however between, this and Ad Hoc Polymorphism is that Ad Hoc Polymorphism "examines" the types ad hoc polymorphism is utilizing a possibly different implementation based on types. So, in standard Parametric Polymorphism, it's the same code running on different types. Meanwhile, in ad hoc polymorphism, it would be different code based on the actual type.

Parametric Polymorphism

Well, parametric polymorphism, like the name says, is just parametric. We specify a function with a generic parameter, then, when we instantiate that function or whatever, we specify our current type, which then gets applied to the function.

Let's see an example:

object GenericPolyPlayground {

  trait GenericStack[T] {
    var elms: List[T] = Nil
    def push(x: T) { elms = x :: elms }
    def peak(): T = elms.head
    def pop(): T =
    {
      val h = elms.head
      elms = elms.tail
      h
    }
  }
}


We have a generic implementation of a stack. We don't specify what type that stack is, and it will always run the operations on a generic list like head or tail. Whatever we put in that GenericStack would get placed on a generic List and thus would run the same operations. Le's try it.

    val intStack = new GenericPolyPlayground.GenericStack[Int] {}
    intStack.push(1)
    println(s"with generic polymorphism it will just pop 1, so boring: ${intStack.pop()}") // it always has the same pop implementation.

    // Output:

    // with generic polymorphism it will just pop 1, so boring: 1    


So you see, we pushed a 1 and it printed 1. Nothing special.

Ad Hoc Polymorphism

With ad hoc polymorphism, we can actually change the behavior of the generic code based on the type we polymorph on! Let's see an example:

object AdHocPolyPlayground {

  trait AdHocStack[T] {
    var elms: List[T] = Nil

    def push(x: T) {
      elms = x :: elms
    }

    def peak(): T = elms.head

    def pop()(implicit crazy: Crazy[T]): T = {
      crazy.omg()
      val h = elms.head
      elms = elms.tail
      h
    }
  }

  trait Crazy[T] {
    def omg()
  }

  implicit val crazyInt: Crazy[Int] = new Crazy[Int] {
    def omg() {
      println("omg i'm crazy")
    }
  }

  implicit val crazyLong: Crazy[Long] = new Crazy[Long] {
    def omg() {println("omg im so long!") }
  }
}


In the above implementation, we call an additional function from within the pop generic implementation: crazy.omg();

And that crazy.omg is different based on the type. You see we have one omg for Int and another for Long, so our generic implementation changes according to the type we polymorph on See the below example:

    val intCrazyStack = new AdHocPolyPlayground.AdHocStack[Int] {}
    intCrazyStack.push(1)
    println(s"with ad hoc polymorphism it will initiate crazy stuff for type int! we change behaviour based on type: ${intCrazyStack.pop()}")

    val longCrazyStack = new AdHocPolyPlayground.AdHocStack[Long] {}
    longCrazyStack.push(1)
    println(s"with ad hoc polymorphism it will initiate a different crazy stuff for long! we change generic behaviour based on type: ${longCrazyStack.pop()}")

  }

  // and the output:

  omg i'm crazy
  with ad hoc polymorphism it will initiate crazy stuff for type int! we change behaviour based on type: 1
  omg im so long!
  with ad hoc polymorphism it will initiate a different crazy stuff for long! we change generic behaviour based on   type: 1


Summary

We have three types of polymorphism: subtype, ad hoc, and generic. Subtype is the standard OOP polymorphism. With generic, we specify a generic code to run on various types, and with ad hoc polymorphism, we can change the generic code run based on the actual type polymorphed on!

Polymorphism (computer science) ADS (motorcycle) Hoc (programming language) Scala (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 5 Steps for Getting Started in Deep Learning
  • Integrate AWS Secrets Manager in Spring Boot Application
  • A Gentle Introduction to Kubernetes
  • 10 Most Popular Frameworks for Building RESTful APIs

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: