I've read about Scala having covariant return types for functions.
But what about its argument types? What does FunctionX(T1,...,R)
have to do with all this?
Asked
Active
Viewed 337 times
1

Jacek Laskowski
- 72,696
- 27
- 242
- 420

voluminat0
- 866
- 2
- 11
- 21
-
2The argument types are contravariant. – Michael Zajac Jan 28 '15 at 21:41
-
I found this as an appropriate answer to my question: http://stackoverflow.com/questions/4297019/scala-function-variance-and-overriding – voluminat0 Jan 28 '15 at 22:15
1 Answers
7
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

Jacek Laskowski
- 72,696
- 27
- 242
- 420

Gabriele Petronella
- 106,943
- 21
- 217
- 235