簡體   English   中英

存在類型

[英]existential types

(更新:簡化了代碼,並說明了為什么它應該工作)

如何修復此代碼?:

case class Sub[B <: Seq[_] : Manifest](b: B) {
  def foo[B2 >: B <: Seq[_] : Manifest](other: Sub[B2]) : B2 =  {
    println(manifest[B])
    println(manifest[B2])

    // next line doesn't compile 
    // other.b ++ b
    other.b 
  }

}

如果我取消注釋other.b ++ b行,我會收到錯誤消息:

<console>:13: error: Cannot construct a collection of type That with elements of type Any based on a collection of type Repr.
           other.b ++ b
                   ^

如果我發表評論,代碼會編譯並運行它:

scala> Sub(List(1,2)).foo(Sub(Seq(4,5)))
scala.collection.immutable.List[Int]
scala.collection.Seq[Int]
res0: Seq[Int] = List(4, 5)

所以編譯器知道元素的類型是List[Int]Seq[Int] 連接它們應該沒有問題。

注意:我想保留“B2 >: B”的使用,因為我需要推斷它。

此時您已經丟失了 Seq[_] 的類型,因此您可以獲得的唯一可能的 B 是 Seq[Any]...因此,您可以安全地將 b 歸於 Seq[Any] (b: Seq[Any] ]) ++ b2。

僅僅因為您在 B <: Seq[_] 中保留了 B 並不意味着您可以從序列中恢復存在類型。

如果您不依賴於使用存在類型,這應該有效:

case class Sub[T, B[X] <: Seq[X]](b: B[T]) {
  def foo[B2[X] <: Seq[X]](other: Sub[T,B2]) =
     other.b ++ b
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM