繁体   English   中英

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

[英]Trait Type Parameter Not Recognised In Method

我有这个我面临的问题的模拟示例。


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)
  }

}

我得到这个编译时错误

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)

我期待因为我已将R[_]的超类型指定为Baz[_]将类型R[_]的值传递给需要Baz[A]的方法会解析,但编译器似乎没有这么想。 我在这里不明白什么?

问题是R[_] <: Baz[_]并不意味着你认为它的意思。
它只是暗示应该有一个 class RBaz的子类,这不同于说R[x]是任何类型xBaz[x]的子类型; 这就是你想要的。

值得庆幸的是,该语言确实提供了一种暗示方式,以非常相似的方式: R[x] <: Baz[x]解决了这个问题。


您可以看到这里运行的代码

暂无
暂无

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

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