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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Injecting Implementations With Jakarta CDI Using Polymorphism

Trending

  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • A Modern Stack for Building Scalable Systems
  • Performance Optimization Techniques for Snowflake on AWS
  • Contextual AI Integration for Agile Product Teams
  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.

By 
Tomer Ben David user avatar
Tomer Ben David
·
Apr. 04, 17 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
26.6K 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.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Injecting Implementations With Jakarta CDI Using Polymorphism

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: