【问题标题】:Abstract parametric types in ScalaScala 中的抽象参数类型
【发布时间】:2018-08-01 09:04:16
【问题描述】:

我有:

trait A[B[_]]

我有:

trait Base {
    type AImpl <: ???
    def foo: AImpl
}

这样扩展 Base 的类将定义 A 并实现方法和字段。即:

trait BB[T]
trait AA extends A[BB]

trait Child extends Base {
  override type AImpl = AA
}

我的问题是声明抽象类型AImpl。我试过了:

type AImpl <: A[B[_]] forSome {type B[_]}

但我收到以下编译错误:

B[_] takes no type parameters, expected: one
type AImpl <: A[B[_],_] forSome {type B[_]}

声明这种抽象类型的正确方法是什么?

【问题讨论】:

  • 这不可能是你想要的。具体来说,您可能还想让AImpl 更友好。

标签: scala parametric-polymorphism abstract-type


【解决方案1】:

此代码可以满足您的要求,但我认为您不是故意的:

trait A[B[_]]

trait Base {
  type AImpl <: A[B] forSome { type B[_] }
  def foo: AImpl
}

如果您可以更具体一些,我可能会查明您的问题并提出另一种解决方法。


正如我之前所坚持的,你的意图有很多问题。我很清楚你正在尝试做一些你不应该做的事情。

要解释几个问题,您首先需要了解存在类型。在这里,您正在对 AImpl 进行一定的限制:

type AImpl <: A[B] forSome { type B[_] }

这要求它的实现符合这种类型。但是,这种类型不可能有任何实现,因为

  1. B 隐藏在存在类型内部,因此外部未知;
  2. A 是不变的,因此它强制实现成为 A[B] 的子类型,用于精确隐藏的 B

这两个一起禁止AImpl实现。修复的方法是转A协变:

trait A[+B[_]]

trait Base {
  type AImpl <: A[B] forSome { type B[_] }
  def foo: AImpl
}

trait BB[T]
trait AA extends A[BB]

object Child extends Base {
  override type AImpl = A[BB]

  def foo = ???
}

这段代码编译没有问题。

然而,我不得不再次说,存在量化 B 是一个根本有缺陷的想法,因为在给定的环境中,没有类型安全的方法来恢复 B 了,如果你需要它,更不用说scala 中更高种类的类型不足且格式错误。

【讨论】:

  • 谢谢。你的解决方案几乎可以工作,但它仍然给我错误。我已经更新了我的预期用法。基本上,我想要“类型族”。
  • @Mathsnoob 这个示例代码在我的 IDE 中编译。您可能需要在编译器选项中打开更高种类的类型。不管怎样,让我看看你想要什么。
  • 为什么不能删除A[B[_],_]?很明显,这里的A 是一种(*, *) -&gt; *,这不可能是正确的。目前还不清楚你从这方面想要什么。此外,scala 中的存在类型从根本上被破坏了,而且在大多数情况下,这不是你想要的。那你想解决什么问题?
  • 抱歉给您带来了困惑。以上是我的代码的简化,我也忘了更改错误。你说得对。原来的错误是:A[B[_]] forSome {type B[_]}。我在您的代码上遇到的错误是:Error:(11, 18) overriding type AImpl in trait Base with bounds &lt;: A$A32.this.A[_[_] &lt;: Any]; type AImpl has incompatible type override type AImpl = AA ^ 这是一个要点:gist.github.com/ShahOdin/4bde0c7844589fa7dfaf6a255dfd9a20
  • @Mathsnoob 我已经从我的更新中解决了这个错误。
猜你喜欢
  • 1970-01-01
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
相关资源
最近更新 更多