Scala函数的泛型特性——逆变与协变

deltamaster posted @ Jun 17, 2014 10:22:10 PM in Scala with tags scala 函数 泛型 Functional Programming Liskov 协变 逆变 , 9185 阅读

在Scala(以及其他许多编程语言)中,函数也是对象,可以使用、定义其他对象的地方,也可以使用、定义函数。Scala中的函数,具有apply方法的类的实例,就可以当做函数来使用。其中apply接受的参数就是函数的参数,而apply的返回值就是函数的返回值。

首先给出一个接受一个参数的函数的泛型定义。

trait Function1[-T, +U] {
  def apply(x: T): U
}

这种函数接受一个参数,参数类型为泛型类型T,返回类型为泛型类型U。和其他支持泛型的语言一样,实际定义函数时T和U的类型会被确定下来,不过需要注意的是,这边的T之前有一个“-”,而U之前有一个“+”。

在这里引入关于这个符号的说明,在声明Scala的泛型类型时,“+”表示协变,而“-”表示逆变。

  • C[+T]:如果A是B的子类,那么C[A]是C[B]的子类。
  • C[-T]:如果A是B的子类,那么C[B]是C[A]的子类。
  • C[T]:无论A和B是什么关系,C[A]和C[B]没有从属关系。

根据Liskov替换原则,如果A是B的子类,那么能适用于B的所有操作,都适用于A。让我们看看这边Function1的定义,是否满足这样的条件。假设Bird是Animal的子类,那么看看下面两个函数之间是什么关系:

def f1(x: Bird): Animal // instance of Function1[Bird, Animal]
def f2(x: Animal): Bird // instance of Function1[Animal, Bird]

在这里f2的类型是f1的类型的子类。为什么?

我们先看一下参数类型,根据Liskov替换原则,f1能够接受的参数,f2也能接受。在这里f1接受的Bird类型,f2显然可以接受,因为Bird对象可以被当做其父类Animal的对象来使用。

再看返回类型,f1的返回值可以被当做Animal的实例使用,f2的返回值可以被当做Bird的实例使用,当然也可以被当做Animal的实例使用。

所以我们说,函数的参数类型是逆变的,而函数的返回类型是协变的。

那么我们在定义Scala类的时候,是不是可以随便指定泛型类型为协变或者逆变呢?答案是否定的。通过上面的例子可以看出,如果将Function1的参数类型定义为协变,或者返回类型定义为逆变,都会违反Liskov替换原则,因此,Scala规定,协变类型只能作为方法的返回类型,而逆变类型只能作为方法的参数类型。类比函数的行为,结合Liskov替换原则,就能发现这样的规定是非常合理的。

这种函数的泛型特性对于函数式编程非常有用。尽管C++的泛型在语法层面上不支持协变与逆变,但在C++11的function<U(T)>中,返回类型U和参数类型T也同样遵循与Scala相同的协变与逆变规则。

* 本文在CC BY-SA(署名-相同方式共享)协议下发布。
PR full form 说:
Aug 10, 2022 03:34:02 PM

PR full form is Public Relations which is a practice of arranging the reach of information between companies or individuals or between public and audience. PR is also an art of strategic management of relationships between the targeted audience and companies. PR full form Public relation firms help the individual and businesses such as politicians, influencers, celebrities to promote their build or image of a relation through media. There are various ways where the PR Full form used. This may used when involve in a word, and a sentence framed.

AP 10th Social Quest 说:
Sep 10, 2022 07:30:48 PM

Social Study is most important students to all students of AP 10th Class, here we have provided the study material with solved question bank for all government and private school TM, EM, UM and HM students in chapter wise from past years old exams and we have provided the AP 10th Social Model Paper 2023 Pdf suggested by subject experts. AP 10th Social Question Paper All BSEAP 10th class regular and private course students can follow the list of chapters under SSC Social Study to practice study material with previous question bank to get a better score in summative assessment (SA) and formative assessment (FA) SA-1, SA-2, FA-1, FA-2, FA-3, FA-4 along with Assignments exams previously called Unit Test-1, Unit Test-2, Unit Test-3, Unit Test-4 and Three Months.

charlly 说:
Jan 16, 2023 11:50:44 AM

Scala functions are generic in nature, which means that they can be used with different types of data. This is made possible by two features known as contravariance and covariance. Contravariance allows a function to be used with a narrower type than the one it was originally defined for. So, if a function is defined for a generic type T, it can also be used with a type that is a subtype of T. Covariance, on the other hand, allows a function real estate services Gordon to be used with a broader type than the one it was originally defined for.

CBSE 3rd Class Spli 说:
Aug 21, 2023 07:12:53 PM

CBSE Curriculum is based on the National Curriculum Framework and Provides Opportunities for Students to Achieve Excellence in Learning, CBSE Provides the Syllabus for 3rd Class, This new Syllabus CBSE 3rd Class Split up Syllabus 2024 are Designed Strategically by a Team of Subject Experts and are Prescribed by the Ministry of Human Resource Development, formerly Ministry of Education, is Responsible for the Development of Human Resources in India, Primary Level Syllabus for the Children of has been developed with the Supervision of the Central Board of Secondary Education.

marketing video prod 说:
Aug 29, 2023 01:40:22 AM

From lighting and color palettes to camera angles, every visual element matters. Attention to detail in these areas enhances the overall cinematic effect of your video.Professional videography brings technical expertise to the table. High-quality visuals and expertly captured shots contribute to the overall professionalism of your video.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter