As the error says, your variance annotation of A
is wrong. You cannot use A
in a return type which is a covariant position. Imagine you had another method in Foo
which uses A
in proper contravariant position (as an argument):
trait Foo[-A] {
...
def foo(a: A): Unit
}
Now you can see how this crashes:
Foo[-A]
implies thatFoo[X] <: Foo[Y]
ifX >: Y
- a returned value may be a subtype of the declared return type
- therefore, if
-A
was legal here,compose
might return aFoo[A1]
for someA1 >: A
- say
trait X
andtrait Y extends X { def bar() }
- imagine a
Foo[Y]
wherefoo
callsa.bar()
- consequently it would break if
compose
was allowed to returnFoo[X]
So for you example to compile, A
must be invariant.