scala - 存在类型

标签 scala existential-type

(更新:简化了代码并展示了为什么它应该工作)

我该如何修复此代码?:

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 并不意味着您可以从序列中恢复存在类型。

关于scala - 存在类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6267524/

相关文章:

scala - 使用 Scalaz 过滤带有 bool 值列表的函数列表

class - 即使是 Scala 中简单的序列化示例也不起作用。为什么?

scala - 从 Play 2.0 Scala Controller 中的请求获取表单参数值

haskell - 将函数组合与 RankNTypes 一起使用时出现类型错误

haskell - 如何使用 Linear.V 编写静态类型检查矩阵运算(Haskell)?

scala - Spark 使用递归案例类

scala - RDD 访问另一个 RDD 中的值

haskell - 隐藏 State monad 的类型参数

Scala 编译错误 : not found: type _$1

haskell - 没有存在类型的异构索引结构?