简体   繁体   中英

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 i th element. Each class takes a different datatype (like Int, Double, String etc).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM