2

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

4

1 回答 1

3

如果类接受参数,它们可能Function1. 不幸的是,不是全部

所以你可以写:

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

但这不适用于所有带参数的对象,例如案例类伴随对象。因此,为了解决这个问题,您可以使用结构类型。就像是:

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

基本上我们在这里所做的是接受任何类型的子类型,该子类型有一个apply方法,Int即它需要一个Int参数。

应该注意的是,如果您尝试将输入类型从泛化Int到任意T

于 2017-02-27T05:50:08.367 回答