What is the variance of argument types in Scala?

Deadly 提交于 2019-11-29 17:06:25
Gabriele Petronella

If you look at the documentation for any FunctionX class, you'll see that the return type is co-variant and the argument types are contravariant. For instance, Function2 has the signature:

Function2[-T1, -T2, +R] extends AnyRef

You can spot the - and + before the type parameters, where - means contravariant and + covariant.

This means that given

class Animal
class Dog extends Animal

then

Function1[Animal, Dog] <: Function1[Dog, Dog]
Function1[Dog, Dog] <: Function1[Dog, Animal]

but

Function1[Dog, Animal] </: Function[Dog, Dog]
Function1[Animal, Animal] </: Function[Animal, Dog]

In other words, functions promise no less and require no more

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!