vinayawsm
vinayawsm

Reputation: 865

Parametric polymorphism in scala

I'm trying to implement parametric polymorphism to devolve functions that have case matching statements that use asInstanceOf[]. I need to match the type of arguments to a classes in another package of the project which accepts parameters. I've tried this code:

def abc[A](x: A, i: Int): Any =
{
    x(i)
}

On running, I get an error saying A does not take parameters. How can I match A to few of the classes in project1.package1 folder? These classes are similar to an Array/Vector and x(i) returns ith element. Each class takes a different datatype (like Int, Double, String etc).

Upvotes: 2

Views: 595

Answers (1)

triggerNZ
triggerNZ

Reputation: 4771

If the classes accept parameters, they may be subtypes of Function1. Unfortunately not all

So you could write:

def abc[A <: Function1[Int, _]](x: A, i: Int): Any = {
    x(i)
}

But that doesn't work for all objects that take parameters, for example case class companion objects. So to get around that you could use a structural type. Something like:

 def abc[A <: {def apply(i: Int): Any } ](x: A, i: Int): Any = {
    x(i)
}

Basically what we are doing here is accepting a subtype of any type that has an apply method with an Int i.e. it takes an Int parameter.

It should be noted that the structural type will give you grief if you try to generalise the input type from Int to an arbitrary T

Upvotes: 3

Related Questions