简体   繁体   English

方法中无法识别特征类型参数

[英]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.我期待因为我已将R[_]的超类型指定为Baz[_]将类型R[_]的值传递给需要Baz[A]的方法会解析,但编译器似乎没有这么想。 What am I not understanding here?我在这里不明白什么?

The problem is that R[_] <: Baz[_] doesn't mean what you think it does.问题是R[_] <: Baz[_]并不意味着你认为它的意思。
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 ;它只是暗示应该有一个 class RBaz的子类,这不同于说R[x]是任何类型xBaz[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.值得庆幸的是,该语言确实提供了一种暗示方式,以非常相似的方式: R[x] <: Baz[x]解决了这个问题。


You can see the code running here .您可以看到这里运行的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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