Skip to content
This repository has been archived by the owner on Jun 5, 2023. It is now read-only.

Add case def for runtime polymorphism #142

Open
Lumintorious opened this issue Oct 4, 2020 · 1 comment
Open

Add case def for runtime polymorphism #142

Lumintorious opened this issue Oct 4, 2020 · 1 comment

Comments

@Lumintorious
Copy link

Lumintorious commented Oct 4, 2020

Hello!

Method polymorphism in Scala is resolved at compile-time and is only resolved for variables with explicitly declared types.
My suggestion is to add a case def kind of declaration that searches for all similar implementations in a class/object and builds
a single method that uses match/case entries at runtime to decide a branch.

Example

Say we have the following hierarchy:

class Animal
class Bear extends Animal
class Pet extends Animal
class Cat extends Pet

and we have a collection of Animal that we want to iterate over and do something for each animal.

def pet(a: Animal): Unit = println("Trying to pet an animal")
def pet(b: Bear): Unit = println("The bear bit you, he doesn't like being pet")
def pet(c: Cat): Unit = println("The cat purrs.")

List(new Cat, new Bear, new Animal, new Pet).foreach(pet(_))

But this code would only print the animal branch 4 times because the list contains Animal. If we wanted a more specific behaviour we would use a match statement for each branch in our 1 pet class. How about the case def?:

case def pet(a: Animal): Unit = println("Trying to pet an animal")
case def pet(b: Bear): Unit = println("The bear bit you, he doesn't like being pet")
case def pet(c: Cat): Unit = println("The cat purrs.")

that would get compiled to

def pet(a: Animal): Unit = a match
    case c: Cat => println("The cat purrs.")
    case b: Bear => println("The bear bit you, he doesn't like being pet")
    case a: Animal => println("Trying to pet an animal")

The compiled method's signature takes the broadest union found (in this case Animal is the broadest type and no union is to be made, however if the case def pet(a: Animal) wasn't present at compile time, the method's signature would become Cat | Bear for the sake of match exhaustion.

This would make the code more readable and would bring Scala closer to some other functional programming languages because now you could say:

case def reverse(string: ""): String = ???
case def reverse(string: String): String = ???
// That would become:
def reverse(string: String): String = string match
  case "" => ???
  case s: String => ???

This would also be really cool which is what Scala is.

@bishabosha
Copy link
Member

bishabosha commented Nov 2, 2020

I guess a concern here is that typically in Scala it does not matter in which order a def occurs - but this would be a change to that

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants