簡體   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