简体   繁体   中英

If trait A[+T] extends B, should I be able to pass classes of type A[T] where B is needed?

Here is the exact situation I am in (I do not want to simplify it for fear of missing out the cause of the error):

In the framework I am working in there is a

trait RequestHeader{...}

and another trait

trait Request[+A] extends RequestHeader{...}

There is a function that expects to receive an argument of type:

def f(arg: RequestHeader => Result) = {...}

I would expect to be able to pass in

arg': Request[AnyContent] => Result

However, this causes the compiler to complain. Why is this?

Function1 is contravariant in its input type, which makes sense if you think about it. Consider the following simpler example:

trait Foo
case object Bar extends Foo
case object Baz extends Foo

def f(g: Foo => Foo): Foo = g(Baz)

If I give f a function of type Bar => Foo , it's not going to be able to apply that to Baz . (A function of type Foo => Bar , on the other hand, would be perfectly fine.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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