简体   繁体   中英

Trait Type Parameter Not Recognised In Method

I have this mock example of a problem I am facing.


class Baz[-A](
) {
  def p: Unit = println("hi")
}

def n[A](b: Baz[A]): Unit = b.p

trait Foo[R[_] <: Baz[_]] {

  def m[A](req: R[A]): Unit = {
    n(req)
  }

}

I get this compile time error

no type parameters for method n: (b: Baz[A])Unit exist so that it can be applied to arguments (R[A])
--- because ---
argument expression's type is not compatible with formal parameter type;
found   : R[A]
required: Baz[?A]
n(req)

I was expecting that because I have specified the super type for R[_] to be Baz[_] passing a value of type R[_] to a method that requires a Baz[A] would resolve but the compiler doesn't seem to think so. What am I not understanding here?

The problem is that R[_] <: Baz[_] doesn't mean what you think it does.
It just implies that there should be a class R that is a subclass of Baz , which is different from saying that R[x] is a subtype of Baz[x] for any type x ; which is what you want.

Thankfully, the language does provide a way to imply that, in a very similar way: R[x] <: Baz[x] that fixes the problem.


You can see the code running here .

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