1

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?

2
  • You problem that A is not Int. Try def m(req: R[Int]) Commented May 6, 2021 at 13:42
  • sorry I updated the question - now it shows the problem correctly. I don't understand why the compiler can't understand why R[A] is not a subtype of Baz[A] Commented May 6, 2021 at 13:46

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.