简体   繁体   English

Scala中的参数多态性

[英]Parametric polymorphism in scala

I'm trying to implement parametric polymorphism to devolve functions that have case matching statements that use asInstanceOf[] . 我正在尝试实现参数多态性以扩展具有使用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 . 在运行时,我收到一条错误消息,说A does not take parameters How can I match A to few of the classes in project1.package1 folder? 如何将Aproject1.package1文件夹中的几个类匹配? These classes are similar to an Array/Vector and x(i) returns i th element. 这些类类似于数组/向量,并且x(i)返回第i个元素。 Each class takes a different datatype (like Int, Double, String etc). 每个类采用不同的数据类型(例如Int,Double,String等)。

If the classes accept parameters, they may be subtypes of Function1 . 如果这些类接受参数,则它们可能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. 基本上,我们在这里所做的是接受具有类型为Intapply方法的任何类型的子类型,即它接受一个Int参数。

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 应该注意的是,如果您尝试将输入类型从Int推广到任意T ,则结构类型会让您感到悲伤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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